為什麼 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 日

3 千+ 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.