#include <iostream>
//友元的三种实现
//全局函数做友元
//类做友元
//成员函数做友元
using namespace std;
全局函数做友元
一般来说,在全局函数中实例化类的对象后 可以访问该类的公共成员属性和成员函数
但是在某些特定的场景需要访问该类的私有成员 这个时候可以用友元关键字friend声明
在该类的首句中写 friend 全局函数name eg: friend void test01(int age);
//class Building
//{
// friend void test01();
//public:
// Building()
// {
// settingroom = "客厅";
// badroom = "卧室";
// }
// string settingroom;
//private:
// string badroom;
//};
//void test01()
//{
// Building building;
// cout << "你的好基友正在访问" << building.settingroom << endl;
// cout << "你的好基友正在访问" << building.badroom << endl;
//}
//int main()
//{
// test01();
// cout << "Hello World!" << endl;
// return 0;
//}
//类做友元
class Building
{
friend class GoodGay;
public:
Building()
{
settingroom = "客厅";
bedroom = "卧室";
}
string settingroom;
private:
string bedroom;
};
class GoodGay
{
public:
GoodGay()
{
building = new Building; //new 在堆区开辟内存空间 返回对象指针
}
void visit()
{
cout << "好基友类正在访问:" << building->settingroom << endl;
cout << "好基友类正在访问:" << building->bedroom << endl;
}
Building * building;
};
void test01()
{
GoodGay gg;
gg.visit();
}
int main()
{
test01();
cout << "Hello World!" << endl;
return 0;
}
成员函数做友元
//class Building;
//class GoodGay
//{
//public:
// GoodGay()
// {
// building = new Building; //new 在堆区开辟内存空间 返回对象指针
// }
// void visit01()
// {
// cout << "好基友类正在访问:" << building->settingroom << endl;
// cout << "好基友类正在访问:" << building->bedroom << endl;
// }
// void visit02()
// {
// cout << "好基友类正在访问:" << building->settingroom << endl;
// cout << "好基友类正在访问:" << building->bedroom << endl;
// }
// Building * building;
//};
//class Building
//{
// friend void GoodGay::visit01();
//public:
// Building()
// {
// settingroom = "客厅";
// bedroom = "卧室";
// }
// string settingroom;
//private:
// string bedroom;
//};
//void test01()
//{
// GoodGay gg;
// gg.visit01();
// gg.visit02();
//}
//int main()
//{
// test01();
// cout << "Hello World!" << endl;
// return 0;
//}
C++ 友元 学习笔记
于 2023-09-17 02:29:31 首次发布