代码:
#include <cstdio>
#include <iostream> using namespace std; class A{
public:
~A(){
cout<<"~A()"<<endl;
}
}; class B:public A{
public:
~B(){
cout<<"~B()"<<endl;
}
}; int main(){ A* pA = new B();
delete pA;
cout<<"final"<<endl; return ;
}
输出:
~A()
final
分析:
若将A的析构函数设置为虚函数,则输出
~B()
~A()
final
所以最好将类的析构函数设为虚函数