为什么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 妈妈生日祝福语简短励志