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

更新于: 2019 年 7 月 30 日

20+ K 次阅读

开启你的 事业

完成课程后获得认证

开始吧
广告