***************************************************
更多精彩,歡迎進入:http://shop115376623.taobao.com
***************************************************
大家知道,析構函數是為了在對象不被使用之后釋放它的資源,虛函數是為了實現多態。那么把析構函數聲明為vitual有什么作用呢?請看下面的代碼:
1???????? #include?2?????? using namespace std;
3
4?????? class Base
5?????? {
6?????? public:
7?????? ???????? Base() {};?????? //Base的構造函數
8?????? ??????? ~Base()??????? //Base的析構函數
9?????? ???????? {
10???? ???????? ???????? cout << "Output from the destructor of class Base!" << endl;
11???? ???????? };
12???? ???????? virtual void DoSomething()?
13???? ???????? {
14???? ???????? ???????? cout << "Do something in class Base!" << endl;
15???? ???????? };
16???? };
17????
18???? class Derived : public Base
19???? {
20???? public:
21???? ???????? Derived() {};? ???//Derived的構造函數
22???? ???????? ~Derived()????? //Derived的析構函數
23???? ???????? {
24???? ???????? ???????? cout << "Output from the destructor of class Derived!" << endl;
25???? ???????? };
26???? ???????? void DoSomething()
27???? ???????? {
28???? ???????? ???????? cout << "Do something in class Derived!" << endl;
29???? ???????? };
30???? };
31????
32???? int main()
33???? {
34???? ???????? Derived *pTest1 = new Derived(); ??//Derived類的指針
35???? ???????? pTest1->DoSomething();
36???? ???????? delete pTest1;
37????
38???? ???????? cout << endl;
39????
40???? ???????? Base *pTest2 = new Derived(); ?????//Base類的指針
41???? ???????? pTest2->DoSomething();
42???? ???????? delete pTest2;
43????
44???? ???????? return 0;
45???? }
先看程序輸出結果:
1?????? Do something in class Derived!
2?????? Output from the destructor of class Derived!
3?????? Output from the destructor of class Base!
4??????
5?????? Do something in class Derived!
6?????? Output from the destructor of class Base!
代碼第36行可以正常釋放pTest1的資源,而代碼第42行沒有正常釋放pTest2的資源,因為從結果看Derived類的析構函數并沒有被調用。通常情況下類的析構函數里面都是釋放內存資源,而析構函數不被調用的話就會造成內存泄漏。原因是指針pTest2是Base類型的指針,釋放pTest2時只進行Base類的析構函數。在代碼第8行前面加上 virtual 關鍵字后的運行結果如下:
1?????? Do something in class Derived!
2?????? Output from the destructor of class Derived!
3?????? Output from the destructor of class Base!
4??????
5?????? Do something in class Derived!
6?????? Output from the destructor of class Derived!
7?????? Output from the destructor of class Base!
此時釋放指針pTest2時,由于Base的析構函數是virtual的,就會先找到并執行Derived類的析構函數,然后再執行Base類的析構函數,資源正常釋放, 避免了內存泄漏 。
因此, 只有當一個類被用來作為基類的時候,才會把析構函數寫成虛函數 。