標籤:
代碼一、
#include <iostream>using namespace std;class Base{public: Base(){}; ~Base() { cout << "Base destructor." << endl; };};class Derive : public Base{public: Derive(){}; ~Derive() { cout << "Derive destructor." << endl; };};int main(int argc, char **argv){ cout << "delete pBase" << endl; Base *pBase = new Derive(); delete pBase; cout << "delete pDerive" << endl; Derive *pDerive = new Derive(); delete pDerive; return 0;}
運行結果:
代碼二、
#include <iostream>using namespace std;class Base{public: Base(){}; virtual ~Base() { cout << "Base destructor." << endl; };};class Derive : public Base{public: Derive(){}; ~Derive() { cout << "Derive destructor." << endl; };};int main(int argc, char **argv){ cout << "delete pBase" << endl; Base *pBase = new Derive(); delete pBase; cout << "delete pDerive" << endl; Derive *pDerive = new Derive(); delete pDerive; return 0;}
運行結果:
結論:
基類的解構函式是為了,刪除指向衍生類別對象的基類指標時,會調用衍生類別的解構函式。
只要衍生類別解構函式被調用,之後必定調用基類的解構函式。
疑問:按照C++的記憶體布局,虛函數是由放在虛函數表中的函數指標指向的,由函數指標間接調用的。而且衍生類別中如果定義了虛函數,那麼虛函數表中相應存放指向基類虛函數的指標就會被指向衍生類別虛函數的指標替換。以此實現多態,即用基類指標調用衍生類別函數。
但是解構函式是特殊呢,因為衍生類別的解構函式和基類的解構函式並不重名,因此可能不是這樣處理的,此處還需要深究。
C++之虛解構函式