为什么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
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短