C加加实现【问题描述】声明一个Cat类,使其至少满足以下要求: (1)拥有静态数据成员HowManyCats,记录Cat的个体数目。 (2)声明静态成员函数GetHowMany(),存取HowManyCats。 (3)能够以年龄作为构造函数参数,建立合理的构造函数 (4)能够合理实现程序中猫数量的增减。 (5)设计一个名为creating()的函数,该函数的主要功能为创建一个含有5个指向猫对象的指针数组,用于动态创建5个猫对象,猫的年龄分别为1,2,3,4,5。并显示数组创建前后情况下猫的数量。函数参数自拟。 (6)能够合理创建主程序,该主程序能够在调用函数creating()前后显示猫的数量,在体会静态数据成员和静态成员函数的用法。 【输入形式】该程序无输入,请仔细观察输出 【输出形式】输出结果如下图; before the function,the number of the cat is:0 before the Cat array is created,the number of the cat is:0 after the Cat array is created,the number of the cat is:5 destructing of the cat! destructing of the cat! destructing of the cat! destructing of the cat! destructing of the cat! after the function,the number of the cat is:0
时间: 2024-02-09 07:08:44 浏览: 235
以下是C++的代码实现:
```cpp
#include <iostream>
using namespace std;
class Cat {
private:
int age;
static int HowManyCats;
public:
Cat(int a) : age(a) {
HowManyCats++;
}
~Cat() {
HowManyCats--;
cout << "destructing of the cat!" << endl;
}
static int GetHowMany() {
return HowManyCats;
}
static void SetHowMany(int n) {
HowManyCats = n;
}
};
int Cat::HowManyCats = 0;
void creating() {
cout << "before the Cat array is created,the number of the cat is:" << Cat::GetHowMany() << endl;
Cat* cats[5];
for(int i = 0; i < 5; i++) {
cats[i] = new Cat(i + 1);
}
cout << "after the Cat array is created,the number of the cat is:" << Cat::GetHowMany() << endl;
for(int i = 0; i < 5; i++) {
delete cats[i];
}
}
int main() {
cout << "before the function,the number of the cat is:" << Cat::GetHowMany() << endl;
creating();
cout << "after the function,the number of the cat is:" << Cat::GetHowMany() << endl;
return 0;
}
```
输出结果为:
```
before the function,the number of the cat is:0
before the Cat array is created,the number of the cat is:0
after the Cat array is created,the number of the cat is:5
destructing of the cat!
destructing of the cat!
destructing of the cat!
destructing of the cat!
destructing of the cat!
after the function,the number of the cat is:0
```
在上面的代码中,我们定义了一个Cat类,并在其中使用了静态数据成员和静态成员函数。在创建猫对象时,我们通过构造函数自动增加了猫的数量,同时在猫对象被销毁时,自动减少了猫的数量。在creating()函数中,我们动态创建了5个猫对象,并在创建前后输出了猫的数量。最后,我们在主程序中调用了creating()函数,并输出了最终的猫的数量。
阅读全文