#include #include using namespace std;

class Goods { private: char gd_name[20]; // 商品名称 int weight; // 商品重量 static int total_weight; // 同类商品总重量 public: Goods(char* str, int w) { // 构造函数 strcpy(gd_name, str); weight = w; total_weight += weight; } ~Goods() { // 析构函数 total_weight -= weight; } char* GetN() { // 返回商品名称 return gd_name; } int GetW() { // 返回商品重量 return weight; } static int GetTotalWeight() { // 返回同类商品总重量 return total_weight; } };

int Goods::total_weight = 0; // 静态成员变量初始化

int main() { Goods g1('apple', 2); Goods g2('banana', 3); Goods g3('orange', 4);

cout << 'Total weight of all goods: ' << Goods::GetTotalWeight() << endl; // 输出同类商品总重量

return 0;

}

C++ 类定义:商品管理系统示例

原文地址: https://www.cveoy.top/t/topic/oX6a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录