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
热门推荐
10 幼教专干调动祝福语简短
11 女生 节日祝福语简短大气
12 男生打球祝福语简短霸气
13 写给男生简短的祝福语
14 乔迁仪式文案祝福语简短
15 买房的祝福语高级简短
16 周年蛋糕祝福语简短英语
17 回国了祝福语简短英语
18 给姐妹乔迁祝福语简短