為什麼我們會在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP