类和对象-友元
在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类访问另一个类中私有成员
友元的关键字为friend
友元的三种实现
1、全局函数做友元
2、类做友元
3、成员函数做友元
1、全局函数做友元
#include<iostream>
#include<string>
using namespace std;
class building
{
//全局函数是Building好朋友,可以访问Building中私有成员
friend void greatgay(building* buil);
public:
building()
{
m_sittingroom = 233;
m_bedroom = 137;
}
public:
string m_sittingroom;
private:
string m_bedroom;
};
//全局函数
void greatgay(building *buil)
{
cout << "全局函数在访问:" << buil->m_sittingroom << endl;
cout << "全局函数在访问:" << buil->m_bedroom << endl;
}
void test01()
{
building buil;
greatgay(&buil);
}
int main()
{
void test01();
system("pause");
return 0;
}