|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
using namespace std;
class Animal {
public :
void sleep();
Animal() {
};
~Animal() {
cout << "父类析构函数已调用"<<endl;
};
virtual void breathe() {
cout << "父类:动物在呼吸"<<endl;
}
};
void Animal::sleep() {
cout << "睡觉中"<<'\n';
}
class Fish:public Animal {
public:
Fish() {
}
~Fish() {
cout <<"子类析构函数被调用"<<endl;
}
void breathe() {
cout << "子类:鱼在呼吸"<<endl;
}
};
int main() {
Fish fish;
Animal *ptr= new Fish;
ptr->breathe();
delete ptr;
return 0;
}
这个时候因为没有将子类析构函数声明为 virtual类型,所以会调用父类的析构函数
按理说就输出:
子类:鱼在呼吸
父类析构函数已调用
/****************************************************************/
但是实际结果会输出:
子类:鱼在呼吸
父类析构函数已调用
子类析构函数被调用
父类析构函数已调用
/****************************************************************/
求大佬解释一下为什么? |
|