在程序里,有些私有属性 也想让类外函数或者类进行访问,就需要用到友元的技术
- 友元的目的就是让一个函数或者类 访问另一个类中私有成员
友元关键字为 friend
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include<iostream> using namespace std;
class Building {
friend void goodGay(Building* building); public: Building() { m_BedRoom = "卧室"; m_SittingRoom = "客厅"; }
public: string m_SittingRoom;
private: string m_BedRoom; };
void goodGay(Building *building) { cout << "好基友正在访问 " << building->m_SittingRoom << endl; cout << "好基友正在访问 " << building->m_BedRoom << endl; }
int main() { Building building; goodGay(&building); return 0; }
|