virtual 析構函式的作用

2021-06-22 13:26:28 字數 1650 閱讀 7965

大家知道,析構函式是為了在物件不被使用之後釋放它的資源,虛函式是為了實現多型。那麼把析構函式宣告為vitual有什麼作用呢?請看下面的**:

1         #include 

2       using namespace std;

34       class base

5       ;       //base的建構函式

8               ~base()        //base的析構函式

9                ;

12              virtual void dosomething() 

13              ;

16     };

17    

18     class derived : public base

19     ;     //derived的建構函式

22              ~derived()      //derived的析構函式

23              ;

26              void dosomething()

27              ;

30     };

31    

32     int main()

33    

先看程式輸出結果:

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類的析構函式,資源正常釋放,避免了記憶體洩漏。

因此,只有當乙個類被用來作為基類的時候,才會把析構函式寫成虛函式。

virtual析構函式

當派生類物件撤銷時,一般先呼叫派生類的析構函式,然後再呼叫基類的析構函式。include using namespace std class base class derived public base int main void 執行結果 呼叫基類base的析構函式 如果在主函式中用new運算子建...

析構函式virtual與非virtual區別

析構函式virtual與非virtual區別 作為通常的原則,如果乙個類定義了虛函式,那麼它的析構函式就應當是virtual的。因為定義了虛函式則隱含著 這個類會被繼承,並且會通過基類的指標指向子類物件,從而得到多型性。這個類可能會被繼承,並且會通過基類的指標指向子類物件 因此基類的析構函式是否為虛...

C 基礎 08 virtual析構函式的作用

在物件導向語言中,介面的多種不同的實現方式即為多型。c 可以使用virtual來實現多型。如果不使用virtual的話,c 對成員函式使用靜態聯編,而使用virtual,並且在呼叫函式時是通過指標或引用呼叫,c 則對成員函式進行動態編聯 也就是遲後繫結,執行的時候才確定呼叫哪個物件 關於virtua...