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 次閱讀

開啟你的 事業

完成課程後獲得認證

開始吧
廣告
© . All rights reserved.