Linux C++ 016-友元
本节关键字:Linux、C++、友元及三种实现方式
相关库函数:
友元的概念及关键字 friend
在程序里,有些私有属性也可以让类外特殊的函数或者类进行访问,这就需要用到友元技术。
友元的目的就是让一个函数或者类访问另一个类中私有成员。
友元的三中实现方式
(1) 全局函数做友元
(2) 类做友元
(3) 成员函数做友元
全局函数做友元
// 建筑物类
class Building
{
// 在类内声明goodGay是Building类的友元,可以访问私有成员
friend void goodGay(Buiilding *building);
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom;
private:
string m_BedRoom;
}
void goodGay(Buiilding *building)
{
cout << "好基友的全局函数正在访问:" << building->m_SittingRoom << endl;
cout << "好基友的全局函数正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
Building building;
goodGay(&building);
}
类做友元
class Building
{
friend class GoodGay; //GoodGay类是Building类的友元
public:
Buiilding();
public:
string m_SittingRoom;
private:
string m_BedRoom;
}
class GoodGay
{
public:
GoodGay();
void visit(); //参观函数访问Building中的私有属性
Buiilding *building;
}
// 类外写成员函数
Building::Building
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
// 创建建筑对象
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
GoodGay gg;
gg.visit();
}
成员函数做友元
class Building
{
friend void GoodGay::f_visit(); // 声明是友元的成员函数
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
}
class GoodGay
{
public:
GoodGay();
void visit();
void f_visit(); // 可以访问Building的私有成员
Building *building;
}
// 类外写成员函数
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "visit 函数正在访问:" << building->m_SittingRoom << endl;
//cout << "visit 函数正在访问:" << building->m_BedRoom << endl;
}
void GoodGay::f_visit()
{
cout << "visit 函数正在访问:" << building->m_SittingRoom << endl;
cout << "visit 函数正在访问:" << building->m_BedRoom << endl;
}
void test2()
{
GoodGay gg;
gg.visit();
gg.f_visit();
}
标签:友元,Building,SittingRoom,visit,C++,016,BedRoom,GoodGay
From: https://blog.csdn.net/qq_45157350/article/details/135868405