C ++中的虚拟构造函数
仅当我们具有指向派生类对象的基类指针时,虚拟机制才起作用。
在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 生日开业蛋糕祝福语简短