在程序中,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类访问一个类中的私有成员
友元的关键字为 friend
友元的三种实现
-
全局函数做友元
-
类做友元
-
成员函数做友元
友元成员函数的使用
限定友元类中指定的成员函数才可以访问被友元类的数据。
-
先声明被友元的类
-
定义友元类,并声明友元成员函数
-
定义被友元类,并声明友元成员函数
-
定义友元成员函数
// 声明被友元的类
class CTest;
// 定义友元类,并声明友元成员函数
class CBase
{
public:
void fun(CTest obj);
void fun1(CTest obj);
};
// 定义被友元类,声明被哪一个成员函数友元
class CTest
{
private:
int m_age;
// 为什么被友元类要在友元类的下面声明
// 因为只有在声明完友元类之后,才能知道有哪些成员函数
friend void CBase::fun(CTest obj);
};
// 定义友元成员函数
void CBase::fun(CTest obj)
{
obj.m_age = 20;
}
void CBase::fun1(CTest obj)
{
// 因为这个成员函数没有被声明为 CTest 类的友元成员函数
// 所以这里访问 私有属性就 报错
obj.m_age;
}
int main()
{
return 0;
}
4.4.1 全局函数做友元
#include<iostream>
using namespace std;
//家类
class Building
{
friend void goodGay(Building* building);
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom;
private:
string m_BedRoom;
};
//全局函数
void goodGay(Building* building)
{
cout << "好基友的全局函数正在访问" << building->m_SittingRoom << endl;
cout << "好基友的全局函数正在访问" << building->m_BedRoom << endl;
}
void test()
{
Building building;
goodGay(&building);
}
int main()
{
test();
system("pause");
return 0;
}
4.4.2类做友元
#include<iostream>
using namespace std;
class Building;
class GoodGay
{
public:
void visit()
{
}
Building building;
};
class Building
{
friend class GoodGay;
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom;
private:
string m_BedRoom;
}
int main()
{
system("pause");
return 0;
}
4.4.3 成员函数做友元
#include<iostream>
using namespace std;
class Building;
class GoodGay
{
public:
void visit()
{
}
Building building;
};
class Building
{
friend void GoodGay::visit();
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom;
private:
string m_BedRoom;
};
int main()
{
system("pause");
return 0;
}