2.定义一个货物类Item,其必须的数据成员包括货物名称name、货物重量weight,定义适当的构造函数用于初始化。在货物类中,利用静态数据成员实现统计程序中有效的贷物对象的数目item_count(公有成员)和总重量totalweight(私有成员)。补充必要的其他代码,实现主程序依次创建三个货物类对象,每创建 个货物类对象,输出当前内存中有效的货物数目和总重量。
时间: 2024-02-11 13:06:11 浏览: 31
下面是实现上述要求的代码:
```cpp
#include<iostream>
using namespace std;
class Item{
public:
Item(string n, double w){
name = n;
weight = w;
item_count++;
totalweight += w;
}
static int item_count;
static double totalweight;
string name;
double weight;
};
int Item::item_count = 0;
double Item::totalweight = 0;
int main(){
Item item1("apple", 0.2);
cout << "Current number of items: " << Item::item_count << endl;
cout << "Current total weight: " << Item::totalweight << endl;
Item item2("banana", 0.3);
cout << "Current number of items: " << Item::item_count << endl;
cout << "Current total weight: " << Item::totalweight << endl;
Item item3("orange", 0.25);
cout << "Current number of items: " << Item::item_count << endl;
cout << "Current total weight: " << Item::totalweight << endl;
return 0;
}
```
输出结果为:
```
Current number of items: 1
Current total weight: 0.2
Current number of items: 2
Current total weight: 0.5
Current number of items: 3
Current total weight: 0.75
```
在上述代码中,我们定义了一个`Item`类,包含货物名称`name`和重量`weight`两个成员变量,并且定义了一个静态的`item_count`和`totalweight`变量,用于统计程序中有效的货物对象数目和总重量。在类的构造函数中,每创建一个对象,就会将`item_count`增加1,同时将`totalweight`加上当前对象的重量。在`main`函数中,我们创建了三个货物对象,并输出当前内存中有效的货物数目和总重量。