#include <iostream>
using namespace std;
class Animal{
public:
static int number;
virtual void printCount()=0;
Animal(){
++Animal::number;
}
virtual ~Animal(){ //错误点
--Animal::number;
}
};
class Dog:public Animal{
public:
static int number;
Dog(){
++Dog::number;
}
void printCount(){
cout<< Dog::number<<endl;
}
~Dog(){
--Dog::number;
}
};
class Cat:public Animal{
public:
static int number;
Cat(){
++Cat::number;
}
void printCount(){
cout<< Cat::number<<endl;
}
~Cat(){
--Cat::number;
}
};
void print() {
cout <<
Animal::number << " animals in the zoo, "
<< Dog::number << " of them are dogs, "
<< Cat::number << " of them are cats"
<< endl;
}
int Animal::number = 0;
int Dog::number = 0;
int Cat::number = 0;
int main() {
print(); // 0 0 0
Dog d1, d2; //
Cat c1;
print(); //3 2 1 动物 狗 猫
Dog* d3 = new Dog(); //4 3 1
Animal* c2 = new Cat; //5 3 2 受错误点影响的语句(多态语句)
Cat* c3 = new Cat; //6 3 3
print(); //6 3 3
delete c3;
delete c2; //有问题 受错误点影响的语句
delete d3;
print(); // 3 2 2 受错误点影响的语句
}
错误点
1、不加virtual时程序的输出:
2、加virtual时程序的输出:
3、造成两种不同输出的原因:
参考《Effective C++》条款07:为多态基类声明virtual 析构函数 。