為什麼我們會在 C++ 中需要一個純虛解構函式?


在 C++ 中允許純虛解構函式不存在任何不良影響。必須為純虛解構函式提供一個函式體,因為派生類解構函式將在基類解構函式之前呼叫,所以如果我們不提供函式體,它將在物件析構期間找不到需要呼叫的任何內容,並且會發生錯誤。我們可以透過使用帶有定義的純虛解構函式輕鬆建立一個抽象類。

示例程式碼

 線上演示

#include <iostream>
using namespace std;

class B {
   public: virtual ~B()=0; // Pure virtual destructor
};

B::~B() {
   cout << "Pure virtual destructor is called";
}

class D : public B {
   public: ~D() {
   cout << "~Derived\n";
   }
};

int main() {
   B *b = new D();
   delete b;
   return 0;
}

輸出

~Derived
Pure virtual destructor is called

更新時間: 2019 年 7 月 30 日

752 次瀏覽

開啟你的職業生涯

完成課程以下載證書

開始學習
廣告
© . All rights reserved.