★封閉類:包含成員對象的類
●封閉類構(gòu)造函數(shù)的初始化列表
定義封閉類的構(gòu)造函數(shù)時(shí),添加初始化列表:
類名::構(gòu)造函數(shù)(參數(shù)表):成員變量1(參數(shù)表),成員變量2(參數(shù)表)...
●調(diào)用順序
當(dāng)封閉類對象生成的時(shí)候,
s1:執(zhí)行所有成員對象的構(gòu)造函數(shù)
s2:執(zhí)行封閉類的構(gòu)造函數(shù)
●成員對象的構(gòu)造函數(shù)調(diào)用順序
和成員對象在類中的說明順序一致
與在成員初始化列表中出現(xiàn)的順序無關(guān)
●當(dāng)封閉類的對象消亡時(shí),
s1:先執(zhí)行封閉類的析構(gòu)函數(shù)
s2:執(zhí)行成員對象的析構(gòu)函數(shù)
規(guī)范:
1、出現(xiàn)成員對象時(shí),該類的構(gòu)造函數(shù)要包含對成員的初始化。如果構(gòu)造函數(shù)的成員初始化列表沒有對成員對象初始化時(shí)邪媳,則使用成員對象的缺省構(gòu)造函數(shù)。
2、建立一個(gè)類的對象時(shí)雨效,應(yīng)先調(diào)用其構(gòu)造函數(shù)迅涮。但是如果這個(gè)類有成員對象,則要先執(zhí)行成員對象自己所屬類的構(gòu)造函數(shù)徽龟,當(dāng)全部成員對象都執(zhí)行了自身類的構(gòu)造函數(shù)后叮姑,再執(zhí)行當(dāng)前類的構(gòu)造函數(shù)。
以下是實(shí)例:
#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{
// 這個(gè)類就是所謂的封閉類
//其中包括成員對象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<<"請輸入汽車的價(jià)格:"<<endl
cin>>p;
cout<<"請輸入汽車輪胎的半徑:"<<endl;
cin>>tr;
cout<<"請輸入汽車輪胎的厚度:"<<endl;
sin>>tw;
CCar(p,tr,tw);
return 0;
}
作者:華中師范大學(xué) 計(jì)算機(jī)學(xué)院 蒲東齊
文本作者才疏學(xué)淺据悔,如有錯(cuò)誤传透,請指正!