描述
代码填空,使得程序能够自动统计当前各种动物的数量
#include <iostream>
using namespace std;
// 在此处补充你的代码
void print() {
cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}
int main() {
print();
Dog d1, d2;
Cat c1;
print();
Dog* d3 = new Dog();
Animal* c2 = new Cat;
Cat* c3 = new Cat;
print();
delete c3;
delete c2;
delete d3;
print();
}
样例输入
None
样例输出
0 animals in the zoo, 0 of them are dogs, 0 of them are cats 3 animals in the zoo, 2 of them are dogs, 1 of them are cats 6 animals in the zoo, 3 of them are dogs, 3 of them are cats 3 animals in the zoo, 2 of them are dogs, 1 of them are cats
代码实现
1、定义Animal基类,Dog类和Cat类继承基类
2、开始没有对象就可以通过类::变量名进行访问,说明number类定义为静态成员变量,属于整个类,方便对整个类的某个属性进行管理
3、派生类生成时,需要将基类的总数加一(派生类构造函数中实现)
4、main函数中有通过基类指针进行释放内存空间,为了派生类消亡时,基类的总数也保持一致,需要将基类的析构函数定义为虚函数,这样基类指针释放空间时,会有多态现象,会调用派生类的析构函数,而派生类析构函数会自动调用基类的析构函数
5、另外类中定义的静态成员变量,必须在类外进行声明,不然链接时会报错
class Animal{
public:
static int number;
virtual ~Animal(){
number--;
}
};
int Animal::number=0;
class Dog:public Animal{
public:
static int number;
Dog(){
number++;
Animal::number++;
}
~Dog(){
number--;
}
};
int Dog::number=0;
class Cat : public Animal{
public:
static int number;
Cat(){
number++;
Animal::number++;
}
~Cat(){
number--;
}
};
int Cat::number=0;