c++设计一个Width类,其中包含一个私有静态数据成员count,用于记录全局存在的Width对象的个数。每次创建一个对象则计数器自动加1,每次销毁时,自动减1。然后设计一个专门访问它的静态成员函数NumWidths( ),用于返回当前的count的值。
时间: 2024-02-20 09:59:45 浏览: 27
好的,以下是使用C++编写的Width类的代码:
```c++
#include <iostream>
using namespace std;
class Width {
private:
static int count;
public:
Width() {
count++;
}
~Width() {
count--;
}
static int NumWidths() {
return count;
}
};
int Width::count = 0;
int main() {
Width w1, w2, w3;
cout << "Current number of Width objects: " << Width::NumWidths() << endl;
{
Width w4;
cout << "Current number of Width objects: " << Width::NumWidths() << endl;
}
cout << "Current number of Width objects: " << Width::NumWidths() << endl;
return 0;
}
```
在上面的代码中,Width类有一个私有静态数据成员count,用于记录全局存在的Width对象的个数。每次创建一个对象则计数器自动加1,每次销毁时,自动减1。NumWidths()函数用于返回当前的count的值。
在主函数中,创建了三个Width对象w1、w2、w3,此时count的值应该为3。然后在一个代码块中创建了一个Width对象w4,此时count的值应该为4。最后输出当前的count的值。
希望我的回答能够帮到您,如果您还有其他问题,请随时提出。