为什么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 中考祝福语简短卡片大全