C 建構函式和析構函式的呼叫順序

2021-09-22 06:15:39 字數 1644 閱讀 5899

基類建構函式、物件成員建構函式、派生類本身的建構函式  

派生類本身的析構函式、物件成員析構函式、基類析構函式(與構造順序正好相反) 

區域性物件,在退出程式塊時析構

靜態物件,在定義所在檔案結束時析構

全域性物件,在程式結束時析構 

繼承物件,先析構派生類,再析構父類 

物件成員,先析構類物件,再析構物件成員

#include using namespacestd;

classbase1

~base1(void) private: static intcnt; }; int base1::cnt = 0; classbase2 ~base2(void) private: intnum; }; clas***ample ~example(void) private: intnum; }; class derived:public base1, publicbase2 ~derived(void) private: example ex; static example stex; //example::constructor(1) //不能輸出 static intcnt; }; int derived::cnt = 0; derived ge_a(1,2); //base1::constructor(1) //base2::constructor(1) //example::constructor(2) //derived::constructor(1) static derived gs_b(3,4); //base1::constructor(2) //base2::constructor(3) //example::constructor(4) //derived::constructor(2) int main(void) //static derived gs_b(3,4) 析構 //derived::deconstructor(2) //example::deconstructor(4) // base2::deconstructor(3) // base1::deconstructor(2) //derived ge_a(1,2) 析構 // derived::deconstructor(1) // example::deconstructor(2) // base2::deconstructor(1) // base1::deconstructor(1) //static example stex 析構 //example::deconstructor(1) //不能輸出 

#include using namespacestd;

classa

; ~a(); }; classb ; ~b(); }; class c : publica ; ~c(); private: //static b b; b b; }; class d : publicc ; ~d(); }; int main(void) /*output ----->b b a::constructor b::constructor c::constructor d::constructor c::deconstructor b::deconstructor a::deconstructor ----->static b b a::constructor c::constructor d::constructor c::deconstructor a::deconstructor */

C 建構函式析構函式呼叫順序

在使用建構函式和析構函式時,需要特別注意對它們的呼叫時間和呼叫順序。在一般情況下,呼叫析構函式的次序正好與呼叫建構函式的次序相反 最先被呼叫的建構函式,其對應的 同一物件中的 析構函式最後被呼叫,而最後被呼叫的建構函式,其對應的析構函式最先被呼叫。簡單來說,其建構函式的順序就一句話 基類建構函式 成...

C 建構函式和析構函式的呼叫順序

c 如果沒有分配資源那麼就不一定需要析構函式,否則就需要釋放資源,如下 class vector sz constructor acquire memory vector destructor release memory private double elem elem points to an ...

C 建構函式和析構函式的呼叫順序

析構函式的呼叫順序是從底往上的 1 first,the constructor invokes its base class constructors,首先,是呼叫該類的基類建構函式 2 then,it invokes the member constructors,and 然後是該成員類的建構函式...