1. 友元存在目的
可以让一个函数或者类 访问另外一个类中的私有成员。
2. 友元的实现
2.1 全局函数做友元
在类中声明全局函数,然后在前面加关键字friend。
class Room
{
friend void visit_bed(Room& r); // 声明部分
public:
Room(string sit, string bed) : SittingRoom(sit), BedRoom(bed)
{
cout << "初始化成功!" << endl;
}
public:
string SittingRoom;
private:
string BedRoom;
};
void visit_sit(Room& r)
{
cout << "正在访问" << r.SittingRoom << endl; // 访问公共变量
}
void visit_bed(Room& r)
{
cout << "正在访问" << r.BedRoom << endl; // 访问私有变量
}
2.2 类做友元
在类中声明友类,然后在前面加关键字friend。
class Room
{
friend class Person; // 声明友元
// ...
}
class Person
{
public:
Person()
{
room = new Room("客厅", "卧室");
}
void Visit()
{
cout << "正在访问" << room->SittingRoom << endl; // 访问公共成员变量
cout << "正在访问" << room->BedRoom << endl; // 访问私有成员变量
}
Room* room;
};
2.3 成员函数做友元
// 在类中声明
class Room
{
friend void Person::Visit();
// ...
};
class Person
{
public:
void Visit()
{
// ...
}
};