C++提供一種方法,使類別A可以存取類別B放在private區域的類別成員。
中文翻譯做:友情宣告(friend declaration)。範例如:
class girl
{
public:
girl(string name_,int age_,int s)
{name=name_;age=age_;sweet_score=s;}
friend class boy; //宣告類別boy為友情類別
private:
string name;
int age;
int sweet_score;
};
class boy
{
public:
boy(string name_,int age_){name=name_;age=age_;}
void select(girl g1,girl g2){ //因為類別boy是類別girl的友情類別,所以可以存取類別girl放在private的類別成員
int like1=g1.sweet_score-g1.age;
int like2=g2.sweet_score-g2.age;
if(like1>like2)
{cout<<name<<" like "<<g1.name<<" more than "<<g2.name<<"!!"<<endl;}
else if(like2>like1)
{cout<<name<<" like "<<g2.name<<" more than "<<g1.name<<"!!"<<endl;}
else if(like1==like2)
{cout<<"cannot make decision!!"<<endl;}
}
private:
string name;
int age;
};
void main() //主程式
{
boy boy1("Jack",35);
girl girl1("wiewei",18,80);
girl girl2("nunu",22,85);
boy1.select(girl1,girl2); //顯示 Jack like nunu more than weiwei!!
}
留言列表