close

按此前往C++完整教學目錄

 

 

類別物件的嵌入(embedding)

所謂嵌入,事實上指的是將一類別A物件嵌入類別B內,使之成為類別B類別成員

比如我們將「人(person)」當作一個類別,「衣服(cloth)」當成一個類別,人擁有衣服,故將cloth嵌入person

範例如下:

class cloth //建立一cloth類別

{        

public:

string color;

cloth(){}         

cloth(string color_,int price_){

color=color_; price=price_;}

private:

int price;

};

 

class person  //建立一person類別

{       

public:

person(string name_,int age_)

{

name=name_;age_=age;

is_wear_jacket=false;

is_wear_shirt=false;

}

void wear_jacket (cloth cloth1)

{ jacket =cloth1;is_wear_jacket =true;}

void wear_shirt(cloth cloth1)

{shirt=cloth1;is_wear_shirt=true;}

void take_off_jacket ()

{is_wear_jacket =false;}

void take_off_shirt()

{is_wear_shirt=false;}

void get_wearing_condition()

{

if(is_wear_shirt && is_wear_jacket)

{cout<< name <<" wear "<<shirt.color<<" shirt and"<< jacket.color<<" jacket!"<<endl;

}

else if (is_wear_jacket)

{cout<<name<<" wear "<< jacket.color<<" jacket and no shirt!"<<endl;}

else if (is_wear_shirt)

{cout<<name<<" wear "<<shirt.color<<" shirt and no jacket!"<<endl;}}

 

cloth jacket;   //嵌入一cloth類別物件,名叫jacket

cloth shirt;        //嵌入一cloth類別物件,名叫shirt

private:

string name;

int age;

bool is_wear_jacket;

bool is_wear_shirt;    

};

 

// 主程式在此

person person1("weiwei",18);

cloth cloth1("blue",600);

person1.wear_shirt(cloth1);

person1.get_wearing_condition();  //顯示weiwei wear blue shirt and no jacket!

 

 

上一篇:類別(class) 抽象類別

下一篇:檔案讀寫(io) 簡介

arrow
arrow

    埃伯 發表在 痞客邦 留言(2) 人氣()