定义一个货物类Item,其必须的数据成员包括货物名称name、货物重量weight,定义适当的构造函数用于初始化。 在货物类中,利用静态数据成员实现统计程序中有效的货物对象的数目item_count(公有成员)和总重量totalweight(私有成员)。 补充必要的其他代码,实现主程序依次创建三个货物类对象,每创建一个货物类对象,输出当前内存中有效的货物数目和总重量
时间: 2024-02-09 19:12:56 浏览: 31
好的,这是一个简单的题目,我可以帮您解答。以下是实现代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Item {
public:
Item(string n, double w) {
name = n;
weight = w;
item_count++;
totalweight += weight;
}
static int get_item_count() {
return item_count;
}
double get_weight() {
return weight;
}
static double get_totalweight() {
return totalweight;
}
private:
string name;
double weight;
static int item_count;
static double totalweight;
};
int Item::item_count = 0;
double Item::totalweight = 0;
int main() {
Item item1("item1", 2.5);
cout << "item_count: " << Item::get_item_count() << ", totalweight: " << Item::get_totalweight() << endl;
Item item2("item2", 1.5);
cout << "item_count: " << Item::get_item_count() << ", totalweight: " << Item::get_totalweight() << endl;
Item item3("item3", 3.0);
cout << "item_count: " << Item::get_item_count() << ", totalweight: " << Item::get_totalweight() << endl;
return 0;
}
```
在这个程序中,我们定义了一个Item类,它有两个数据成员name和weight,表示货物的名称和重量。我们还定义了item_count和totalweight两个静态数据成员,用来统计货物类对象的数目和总重量。在每次创建新的货物对象时,构造函数会自动更新这两个静态数据成员。我们还提供了三个静态成员函数,用于获取item_count、totalweight和货物重量。最后,在主程序中,我们创建了三个货物对象,并输出了当前的item_count和totalweight。
希望这个例子能够帮助您理解静态数据成员的用法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)