友元:在程序里,私有属性类外不可访问,如果有些私有属性也想让类外的一些特殊函数或者类访问,就要使用友元
友元可以让一个函数或者类访问另一个类中的私有成员
关键字为 friend
友元的三种实现:
全局函数做友元
class Building
{
friend void good(Building &building);//表明该全局函数是友元
private:
int a;
}
void good(Building &building)
{
cout<<building.a<<endl;
}
类做友元
假设有一个good类
替代上例中的位置
写为
friend class good;
成员函数做友元
假设有一个good类,类中有一个成员函数g
那么替代上述位置为
friend void good::g();