1.構造函數
C++中的構造函數是用於初始化類的各種變量以及分配資源等。主要的注意事項是:
(1)在繼承關系中先初始化父類對象后初始化子類對象。
(2)在一個類中按照變量的聲明順序,對類中的變量進行初始化。
(3)初始化過程中,可以使用已經被初始化的對象去初始化其他的對象。
2.析構函數
析構函數與構造函數作用相反,當對象脫離其作用域時(例如對象所在的函數已調用完畢),系統自動執行析構函數。
析構函數往往用來做“清理善后” 的工作(例如在建立對象時用new開辟了一片內存空間,應在退出前在析構函數中用delete釋放)。
調用順序與構造函數正好相反,先析構子類(釋放子類資源),在析構父類(釋放父類資源)。
3.虛析構函數
虛析構函數可以認為是特殊的析構函數,主要作用在繼承關系中。
若B是A的子類: A *a=new B;
delete a;
如果A的析構函數是non-vartual,則只會調用A的析構函數,這樣B的資源沒有釋放,就會有內存泄露;
如果A的析構函數是vartual,則只會先調用A的析構函數,再調用B的析構函數。
(見C++ 在繼承中虛函數、純虛函數、普通函數,三者的區別)
4.代碼示例
1 #include <iostream> 2 using namespace std; 3 class A{ 4 public: 5 A(int _a):a(_a){ 6 cout<<"A constructed function"<<endl; 7 } 8 9 virtual ~A(){ 10 cout<<"A destructor function"<<endl; 11 } 12 13 int getA(){ 14 return a; 15 } 16 private: 17 int a; 18 }; 19 20 class B:public A{ 21 public: 22 B(int _a,int _b):b(_b),A(_a){ 23 cout<<"B constructed function"<<endl; 24 } 25 26 ~B(){ 27 cout<<"B destructor function"<<endl; 28 } 29 30 int getAplusB(){ 31 return b+getA(); 32 } 33 private: 34 int b; 35 }; 36 37 int main(void) 38 { 39 B b(2,3); 40 cout<<b.getAplusB()<<endl; 41 cout<<"***********************************"<<endl; 42 A *a=new B(2,3); 43 cout<<"***********************************"<<endl; 44 delete a; 45 return 0; 46 }
執行輸出:

