★封閉類:包含成員對象的類
●封閉類構造函數的初始化列表
定義封閉類的構造函數時,添加初始化列表:
類名::構造函數(參數表):成員變量1(參數表),成員變量2(參數表)...
●調用順序
當封閉類對象生成的時候,
s1:執行所有成員對象的構造函數
s2:執行封閉類的構造函數
●成員對象的構造函數調用順序
和成員對象在類中的說明順序一致
與在成員初始化列表中出現的順序無關
●當封閉類的對象消亡時,
s1:先執行封閉類的析構函數
s2:執行成員對象的析構函數
規范:
1、出現成員對象時,該類的構造函數要包含對成員的初始化。如果構造函數的成員初始化列表沒有對成員對象初始化時,則使用成員對象的缺省構造函數。
2、建立一個類的對象時,應先調用其構造函數。但是如果這個類有成員對象,則要先執行成員對象自己所屬類的構造函數,當全部成員對象都執行了自身類的構造函數后,再執行當前類的構造函數。
以下是實例:
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
class CTyre{
private:
int radius;
int width;
public:
CTyre(int r,int w):radius(r),width(w){};
CTyre(){ cout<<"CTyre contructor"<<endl;
~CTyre(){ cout<<"CTyre destructor"<<endl;
};
class CEngine{
public:
CEngine(){ cout<<"CEngine contructor"<<endl;
~CEngine(){ cout<<"CEngine destructor"<<endl;
};
class CCar{
// 這個類就是所謂的封閉類
//其中包括成員對象CEngine和CTyre
private:
int price;
CTyre tyre;
CEngine engine;
public:
CCar(int p, int tr,int tw );
};
CCar::CCar(int p, int tr,int tw ):price(p),tyre(tr,tw){};
int main(){
int p,tr,tw;
cout<<"請輸入汽車的價格:"<<endl
cin>>p;
cout<<"請輸入汽車輪胎的半徑:"<<endl;
cin>>tr;
cout<<"請輸入汽車輪胎的厚度:"<<endl;
sin>>tw;
CCar(p,tr,tw);
return 0;
}
作者:華中師范大學 計算機學院 蒲東齊
文本作者才疏學淺,如有錯誤,請指正!