为什么 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP