在程序里,有些私有属性 也想让类外函数或者类进行访问,就需要用到友元的技术

  • 友元的目的就是让一个函数或者类 访问另一个类中私有成员

友元关键字为 friend

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
using namespace std;


class Building;
class GoodGay {
public:
GoodGay();
void visit();//参观函数 访问Building中的属性
Building* building;
};

class Building {
//GoodGay是本类的好基友,可以访问本类中私有成员
friend class GoodGay;
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};

//类外写成员函数
Building::Building() {
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}

GoodGay::GoodGay() {
building = new Building; //创建建筑物对象
}

void GoodGay::visit() {
cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}


int main() {
GoodGay gg;
gg.visit();
return 0;
}