C++的虛構(gòu)函數(shù)可以定義為虛函數(shù),這個(gè)在類需要繼承的時(shí)候是至關(guān)重要的。 比如: #include <iostream>using namespace std;class Base {public: void hello() { cout << 'helloworld' << endl; }};class Derived: public Base {public: Derived(): Base() { } ~Derived() { cout << 'Derived destructor.' << endl; }};int main() { Base* pBase = new Derived(); pBase->hello(); delete pBase; return 0;} ![]() 可以看到,Base class沒有定義析構(gòu)函數(shù)函數(shù),當(dāng)我們delete的時(shí)候使用Base的指針的時(shí),Derived類的析構(gòu)函數(shù)不會(huì)被調(diào)用。 ![]() 現(xiàn)在我們定義一個(gè)析構(gòu)函數(shù):
![]() 運(yùn)行結(jié)果如下,可以看到Base的析構(gòu)函數(shù)確實(shí)被調(diào)用了,但是Derived析構(gòu)函數(shù)還是沒有調(diào)用。 ![]() 最好我們把析構(gòu)函數(shù)申明為虛函數(shù): class Base {public: void hello() { cout << 'helloworld' << endl; } virtual ~Base() { cout << 'Base destructor' << endl; }}; ![]() 這次才真正把子類的析構(gòu)函數(shù)給調(diào)用了: ![]() 所以在C++語言里面,如果沒有特殊原因,還是建議把析構(gòu)函數(shù)定義為虛函數(shù)。 |
|