文章目录
- 1.全局函数做友元
- 代码
- 运行结果
- 2.类做友元
- 代码
- 运行结果
1.全局函数做友元
思路分析:
正常情况下,全局函数visit()中的ROOM 类变量r是访问不到Building类中的私有成员的。但是通过在Building类中添加使用全局函数做友元,即可访问私有成员。
friend void visit();/*!!!!!全局函数做友元!!!!!!*/
代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;class Building
{friend void visit();/*!!!!!全局函数做友元!!!!!!*/public:Building(){livingroom = "客厅";bedroom = "卧室";}
public:string livingroom;
private:string bedroom;
};class ROOM
{
public:ROOM(){building = new Building;printf("Room 执行构造函数!\n");}~ROOM(){delete building;printf("Room 执行析构函数!\n");}Building* building;
};void visit()
{ROOM r;cout << "r 访问 livingroom : " << r.building->livingroom << endl;cout << "r 访问 bedroom : " << r.building->bedroom << endl;
}int main()
{ visit();return 0;
}
运行结果
2.类做友元
思路分析:
正常情况下,成员函数visit()中成员变量building是访问不到Building类中的私有成员的。但是通过在Building类中添加使用类做友元,即可访问私有成员。
代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;class Building
{friend class ROOM;/*!!!!!类做友元!!!!!!*/public:Building(){livingroom = "客厅";bedroom = "卧室";}
public:string livingroom;
private:string bedroom;
};class ROOM
{
public:ROOM(){building = new Building;printf("Room 执行构造函数!\n");}void visit();/*成员函数*/~ROOM(){delete building;printf("Room 执行析构函数!\n");}Building* building;
};void ROOM::visit()/*类成员函数,类外定义*/
{cout << "访问 livingroom : " << this->building->livingroom << endl;cout << "访问 bedroom : " << this->building->bedroom << endl;
}void test()
{ROOM p;p.visit();
}int main()
{ test();return 0;
}