友元函数
全局函数作为友元函数
- 利用
friend 关键字让全局函数goodGay 作为本类好朋友,可以访问私有成员 friend void goodGay(Building * buliding);
#include <string>
class Building
{
friend void goodGay(Building * buliding);
public:
Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
string m_SittingRoom;
private:
string m_BedRoom;
};
void goodGay( Building * buliding)
{
cout << "好基友正在访问:" << buliding->m_SittingRoom << endl;
cout << "好基友正在访问:" << buliding->m_BedRoom << endl;
}
void test()
{
Building buliding;
goodGay(&buliding);
}
类作为友元类
让goodGay 访问Building 类的私有属性,需要将goodGay 类作为Building 的友元类,在类Building 中添加friend class GoodGay
#include <string>
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
Building* m_building;
};
class Building
{
friend class GoodGay;
public:
Building();
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
this->m_building = new Building;
}
void GoodGay::visit()
{
cout << "好基友正在访问: " << this->m_building->m_SittingRoom << endl;
cout << "好基友正在访问: " << this->m_building->m_BedRoom << endl;
}
void test()
{
GoodGay gg;
gg.visit();
}
类中的成员函数作为友元函数
- 让
GoodGay 类中的 visit 成员函数作为友元 friend void GoodGay::visit();
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
void visit2();
Building* m_building;
};
class Building
{
friend void GoodGay::visit();
public:
Building();
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
this->m_building = new Building;
}
void GoodGay::visit()
{
cout << "好基友正在访问: " << this->m_building->m_SittingRoom << endl;
cout << "好基友正在访问: " << this->m_building->m_BedRoom << endl;
}
void test()
{
GoodGay gg;
gg.visit();
}
|