一、文章来由
同样项目中是遇到这个问题~~
二、直接上代码来的清楚
#include <iostream>
using namespace std;
class Father
{
public:
Father() {
cout<<"父类诞生了"<<endl;
}
~Father() {
cout<<"父类挂了"<<endl;
}
protected:
private:
};
class Kid : public Father
{
public:
Kid() {
cout<<"子类诞生了"<<endl;
}
~Kid() {
cout<<"子类挂了"<<endl;
}
protected:
private:
};
int main()
{
Father *f = new Kid();
delete f; //只delete父类,子类不会被析构
cout<<endl;
Father *f1 = new Kid();
delete (Kid *)f1;
return 0;
}
这样在调用父类析构函数时,并不会析构子类,于是运行结果如下:
但是如果让父类的析构函数是virtual的,就可以正常析构子类,可见多态在c++里面有多强大~~
virtual ~Father() {
cout<<"父类挂了"<<endl;
}