请用C++设计一个Dog类,它用静态数据成员Dogs记录Dog的个数。静态成员函数GetDogs用来存取Dogs。设计并测出此类
时间: 2024-01-22 10:19:21 浏览: 21
以下是C++设计的Dog类代码:
```c++
#include <iostream>
using namespace std;
class Dog {
private:
static int Dogs;
public:
Dog() {
Dogs++;
}
~Dog() {
Dogs--;
}
static int GetDogs() {
return Dogs;
}
};
int Dog::Dogs = 0;
int main() {
Dog d1, d2;
cout << "Number of dogs: " << Dog::GetDogs() << endl;
{
Dog d3;
cout << "Number of dogs: " << Dog::GetDogs() << endl;
}
cout << "Number of dogs: " << Dog::GetDogs() << endl;
return 0;
}
```
在这个Dog类中,我们使用了一个静态数据成员Dogs来记录Dog的个数,以及一个静态成员函数GetDogs来存取Dogs。在构造函数中,每当创建一个Dog对象时,Dogs的值就会自增;在析构函数中,每当销毁一个Dog对象时,Dogs的值就会自减。在测试代码中,我们创建了三个Dog对象,分别输出当前Dog的数量,再销毁一个Dog对象后再次输出当前Dog的数量。运行结果如下:
```
Number of dogs: 2
Number of dogs: 3
Number of dogs: 2
```