環(huán)境:
編譯器:CLion2021.3;操作系統(tǒng):macOS Ventura 13.0.1
在類中定義的成員屬性往往是private,外界是無法訪問的。若有特殊需求想讓外界可以訪問這些私有屬性,可以把允許訪問的這個(gè)外界設(shè)置為本類的友元。
一、全局函數(shù)做友元class Building {//告訴編譯器 goodGay全局函數(shù) 是 Building類的好朋友,可以訪問類中的私有內(nèi)容
friend void goodGay(Building *building);
public:
string m_SittingRoom; //客廳
private:
string m_BedRoom; //臥室
public:
Building() {this->m_SittingRoom = "客廳";
this->m_BedRoom = "臥室";
}
};
void goodGay(Building *building) {cout<< "好基友正在訪問: "<< building->m_SittingRoom<< endl;//ok
cout<< "好基友正在訪問: "<< building->m_BedRoom<< endl;//ok,若不將goodGay設(shè)為友元?jiǎng)terr
}
二、類做友元class Building {//告訴編譯器 goodGay類是本類的好朋友,可以訪問到Building類中私有內(nèi)容
friend class goodGay;
public:
string m_SittingRoom; //客廳
private:
string m_BedRoom;//臥室
public:
Building();
};
class goodGay {private:
Building *building;
public:
goodGay();
void visit();//訪問Building的屬性
};
Building::Building() {//類外實(shí)現(xiàn)成員函數(shù)
this->m_SittingRoom = "客廳";
this->m_BedRoom = "臥室";
}
goodGay::goodGay() {building = new Building;
}
void goodGay::visit() {cout<< "好基友正在訪問"<< building->m_SittingRoom<< endl;//ok
cout<< "好基友正在訪問"<< building->m_BedRoom<< endl;//ok
}
三、成員函數(shù)做友元class Building {//告訴編譯器 goodGay類中的visit成員函數(shù) 是Building好朋友,可以訪問私有內(nèi)容
friend void goodGay::visit();
public:
string m_SittingRoom; //客廳
private:
string m_BedRoom;//臥室
public:
Building();
};
class goodGay {private:
Building *building;
public:
goodGay();
void visit(); //只讓visit函數(shù)作為Building的好朋友,可以發(fā)訪問Building中私有內(nèi)容
void visit2();
};
Building::Building() {this->m_SittingRoom = "客廳";
this->m_BedRoom = "臥室";
}
goodGay::goodGay() {building = new Building;
}
void goodGay::visit() {cout<< "好基友正在訪問"<< building->m_SittingRoom<< endl;
cout<< "好基友正在訪問"<< building->m_BedRoom<< endl;
}
void goodGay::visit2() {cout<< "好基友正在訪問"<< building->m_SittingRoom<< endl;
// cout<< "好基友正在訪問"<< building->m_BedRoom<< endl;//err,因?yàn)橹宦暶髁藇isit是友元而沒有把visit2聲明為友元
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購,新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧