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

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

友元关键字为 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
45
46
47
48
49
50
51
#include <iostream>
using namespace std;


class Building;
class GoodGay {
public:
GoodGay();
void visit();//可以访问Building中私有成员
void visit2();//不可以访问Building中私有成员
Building *building;
};

class Building {
friend void GoodGay::visit();//告诉编译器 GoodGay类中的visit成员函数是Building类的好基友,可以访问私有内容
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;
}

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


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