题目:
总时间限制:
1000ms 内存限制: 65536kB-
描述
-
代码填空,使得程序能够自动统计当前各种动物的数量
-
#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();
}
输入无输出0 animals in the zoo, 0 of them are dogs, 0 of them are cats3 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样例输入
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
答案:
#include <iostream>
using namespace std;
class Animal
{
public:
static int number;
Animal(){
number++;
}
virtual ~Animal()//如果不加virtual,删除c2的时候就不能调用Cat的析构函数了
{
number--;
}
};
class Dog:public Animal
{
public:
static int number;
Dog()
{
number++;
}
~Dog()
{
number--;
}
};
class Cat:public Animal
{
public:
static int number;
Cat()
{
number++;
}
~Cat()
{
number--;
}
};
int Animal::number=0,Dog::number=0,Cat::number=0; //静态成员变量只能在类外初始化,不能在类里面!!!
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();
}
思考:
1.为什么父类的析构函数不定义成虚函数,删除c2的时候就不会调用~Cat()了?而为什么即使把父类的析构函数定义成虚函数,调用子类的析构函数后仍然会调用负类的虚函数?
首先看下虚函数的作用
析构函数执行时先调用派生类的析构函数,其次才调用基类的析构函数。如果析构函数不是虚函数,而程序执行时又要通过基类的指针去销毁派生类的动态对象,那么用delete销毁对象时,只调用了基类的析构函数,未调用派生类的析构函数。这样会造成销毁对象不完全。
2.为什么静态成员变量在类中初始化会出错?
看上面的代码可知,静态成员变量在类中的只是一个声明,定义和初始化要在类外进行的,至于为什么我的理解是,为了防止每生成一个新对象,静态成员变量的重复定义和初始化吧。