C ++中的虚拟析构函数
使用指向基类的指针删除派生类对象,应使用虚拟析构函数定义基类。
范例程式码
#include<iostream> using namespace std; class b { public: b() { cout<<"Constructing base \n"; } virtual ~b() { cout<<"Destructing base \n"; } }; class d: public b { public: d() { cout<<"Constructing derived \n"; } ~d() { cout<<"Destructing derived \n"; } }; int main(void) { d *derived = new d(); b *bptr = derived; delete bptr; return 0; }
输出结果
Constructing base Constructing derived Destructing derived Destructing base