C++面向物件入門(三十五)虛解構函式
阿新 • • 發佈:2020-09-01
虛解構函式: 使用virtual關鍵字修飾的解構函式
C++不支援虛建構函式, 但支援虛解構函式, 由於解構函式沒有引數, 一個類只能有一個虛解構函式
虛解構函式的必要性: 使用基類的引用或者指向基類型別的指標呼叫解構函式完成派生類物件的析構(delete操作符自動呼叫物件的解構函式)
程式碼示例:
#include <iostream> using namespace std; /* 虛解構函式: 使用virtual關鍵字修飾的解構函式 C++不支援虛建構函式, 但支援虛解構函式, 由於解構函式沒有引數, 一個類只能有一個虛解構函式 虛解構函式的必要性: 使用基類的引用或者指向基類型別的指標呼叫解構函式完成派生類物件的析構(delete操作符自動呼叫物件的解構函式) */ class A52 { public: A52(); virtual ~A52(); }; class B52 :public A52 { public: int*pb; B52(int b); virtual ~B52(); }; class C52 { public: C52(); ~C52(); }; class D52 :public C52 { public: int *pd; D52(int d); ~D52(); }; int main() { A52 *a = new B52(3); delete a; C52 *c = new D52(5); delete c; system("pause"); } A52::A52() { } A52::~A52() { cout << "~A52()" << endl; } B52::B52(int b) { pb = new int; *pb = b; } B52::~B52() { delete pb; cout << "~B52()" << endl; } C52::C52() { } C52::~C52() { cout << "~C52()" << endl; } D52::D52(int d) { pd = new int; *pd = d; } D52::~D52() { delete pd; cout << "~D52()" << endl; }