友元

类的友元函数 (friend) 是定义在类外部, 但是有权限访问类的所有私有 (private) 成员和保护 (protected) 成员

公有成员和私有成员的概念:

  • 公有成员 (public) : 在类外可以访问
  • 私有成员 (private): 只有本类中的函数可以访问

友元 (friend) 可以访问与其有好友关系的类中的私有成员 (有限制的共享).

友元包括友元函数和友元类:

  • 友元函数: 如果在本类以外的其他地方定义的函数, 在类体重用 friend 进行声明. 此函数就称为本类的有元函数, 友元函数可以访问这个类中的私有成员
  • 友元类: 类 A 将另一个类 B 声明为其友元类, 友元类 B 中的所有函数都是 A 类的友元函数, 可以访问 A 类中的所有成员

友元函数

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
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;
class student
{
public:
student(string &name, int &age)
{
my_name = name;
my_age = age;
}
friend void who_are_you(student &s);

private:
string my_name;
int my_age;
};

void who_are_you(student &s)
{
cout << "name: " << s.my_name << endl;
cout << "age: " << s.my_age << endl;
}

int main()
{
string name = "张三";
int age = 18;
student s(name,age);
who_are_you(s);
return 0;
}

友元类

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
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;
class teacher;
class student
{
public:
student(string &name, int &age)
{
my_name = name;
my_age = age;
}

friend class teacher;

private:
string my_name;
int my_age;
};

class teacher
{
public:
void who_are_you(student &s)
{
cout << "name: " << s.my_name << endl;
cout << "age: " << s.my_age << endl;
}
};

int main()
{
string name = "张三";
int age = 18;
student s(name,age);
teacher t;
t.who_are_you(s);
return 0;
}

总结

  • 友元包含友元函数和友元类
  • 友元是C++提供的一种破坏数据封装和数据隐藏的机制。
  • 通过将一个模块声明为另一个模块的友元,一个模块能够引用到另外一个模块中本是被隐藏的信息。
  • 为了确保数据的完整性,及数据封装与隐藏的原则,
    建议尽量不使用或少使用友元。

友元
https://carl-5535.github.io/2022/03/30/C++/友元/
作者
Carl Chen
发布于
2022年3月30日
许可协议