C++友元

SkyLeech lol

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

友元的关键字为friend

友元的三种实现

  • 全局函数做友元

  • 类做友元

  • 成员函数做友元

全局函数做友元

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Building{
//告诉编译器goodGay全局函数是Building类的好朋友,可以访问类中的私有内容
friend void goodGay(Building *building);

public:
string m_SittingRoom;//客厅

Building(){
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
private:
string m_BedRoom;//卧室
};

void goodGay(Building *building){
cout << "好基友正在访问:" << building->m_SittingRoom << endl;
cout << "好基友正在访问:" << building->m_BedRoom << endl;
}

类做友元

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
class Building;

class GoodGay {
public:
GoodGay();

void visit();

Building *building;
};

class Building {
//GoodGay类是本类的好朋友,可以访问本类中私有成员
friend class GoodGay;

public:
string m_SittingRoom;//客厅

Building() {
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}

private:
string m_BedRoom;//卧室
};

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

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

void test01() {
GoodGay gg;
gg.visit();
}

成员函数做友元

  • 标题: C++友元
  • 作者: SkyLeech
  • 创建于 : 2024-05-29 15:05:33
  • 更新于 : 2024-05-29 15:34:08
  • 链接: https://blog.skyleech.me/2024/05/29/C++友元/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论