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 同学道别祝福语简短