c c 整理析構函式

2021-08-07 08:07:52 字數 2222 閱讀 2923

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

[cpp]view plain

copy

"font-size:18px;"

>#include 

using

namespace

std;  

class

base  

//base的建構函式

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

virtual

void

dosomething()  

};  

class

derived : 

public

base  

//derived的建構函式

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

void

dosomething()  

};  

intmain()  

程式輸出:

[cpp]view plain

copy

"font-size:18px;"

>

dosomething in 

class

derived  

output from the destructor of class

derived  

output from the destructor of class

base  

dosomething in 

class

derived  

output from the destructor of class

base

**37行可以正常釋放pt1的資源,但是**41行並沒有正常釋放pt2的資源,從結果看,derived類的析構函式並沒有被呼叫。通常情況下,類的析構函式裡面都是釋放記憶體資源,而析構函式不被呼叫的話就會造成記憶體洩漏。原因是指標pt2是base型別的指標,釋放pt2時只進行base類的析構函式。在**第9行加上virtual關鍵字後:

[cpp]view plain

copy

dosomething in 

class

derived  

output from the destructor of class

derived  

output from the destructor of class

base  

dosomething in 

class

derived  

output from the destructor of class

derived  

output from the destructor of class

base  

此時釋放指標pt2時,由於base的析構函式是virtual的,就會先找到並執行derived類的析構函式,然後執行base類的析構函式,資源正常釋放,避免了記憶體洩漏。

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

[cpp]view plain

copy

#include 

using

namespace

std;  

class

a    

~a() ;  

class

b : 

public

a    

~b();  

intmain()  

本體考查的是析構函式的執行順序。析構函式的執行順序與建構函式的執行順序相反。

main()函式中定義了兩個類b的物件,它們的基類是a。由於這兩個物件都是棧中分配的,當main()函式退出時會發生析構,又因為obj1比obj2先宣告,所以obj2先析構。它們的順序是首先執行b的析構函式,然後執行a的析構函式。

程式輸出:

[cpp]view plain

copy

destructor b!7  

destructor a!6  

destructor b!0  

destructor a!5  

析構函式(整理)

新的概念 析構函式 回憶 建構函式的作用 初始化變數 為變數分配空間 新知 析構函式的作用 銷毀變數 釋放變數占用的空間 析構函式的特徵 命名方式 類名 無返回型別 void 也沒有 類似建構函式 沒有引數,因此不能被過載 沒有明顯定義時,系統呼叫預設析構函式 何時呼叫析構函式?當物件的生命週期結束...

C C 筆記 之建構函式,析構函式

構造方法用來初始化類的物件,與父類的其它成員不同,它不能被子類繼承 子類可以繼承父類所有的成員變數和成員方法,但不繼承父類的構造方法 因此,在建立子類物件時,為了初始化從父類繼承來的資料成員,系統需要呼叫其父類的構造方法。如果沒有顯式的建構函式,編譯器會給乙個預設的建構函式,並且該預設的建構函式僅僅...

C C 複習之 虛析構函式

以上程式的執行結果 c 中當派生類的物件撤銷時,一般先執行基類的建構函式,然後執行派生類的析構函式。以上程式的執行結果是符合預期的,再看以下 以上 執行結果 執行結果可以看到,本程式只執行了基類的析構函式,而沒有執行派生類的析構函式。主函式中,用new運算子建立了乙個派生類的無名物件,並將乙個基類的...