#include <iostream>
using namespace std;
class Base{
public:
virtual ~Base() {cout<<"~B"<<endl;}
};
class Derived:public Base{
public:
virtual ~Derived() {cout<<"~D"<<endl;}
};
int main (){
Base *b=new Derived;
delete b;
}以上代码执行结果是:
~D
~B
对于析构函数使用虚函数的解释,是这样的,因为是使用语句 Base *b=new Derived;来创建的对象b,如果,我们不把析构函数声明为虚函数,那么实际上,在对象生命周期结束时,调用的将只是基类Base的析构函数,而派生类Derived的析构函数将是不调用的,你可以试验一下,此时,只打印~B。而我们为了正确地释放对象,所以要将析构函数声明为虚函数,这时,基类和派生类的析构函数就都会调用了。
浙公网安备 33010602011771号