keyword-friend
# 介绍
最近在做 CS106L Assignment2 实验实现 HashMap,在 hashmap.cpp 中看到了将类 HashMapIterator 声明为 friend ,所以就学习了一些 keyword friend 的用法。
# 概念
假设有定义类 A,类 B 和函数 C,那么类 B 和函数 C 都无法访问类 A 中的私有成员。
但是如果我们在类 A (MyClass) 中声明类 C (AnotherClass) 为 friend, 那么类 C 就可以访问类 A 的私有成员变量,使用方法举例如下:
class MyClass{
friend class AnotherClass;
private:
int secret;
}
class AnotherClass{
public:
void getSecret(MyClass mc){
return mc.secret;
}
}
2
3
4
5
6
7
8
9
10
11
12
为什么设计 friend class 呢?通过 friend class 读写 class 的 private 变量不是破坏了类的封装性了吗?
为什么不给类 A 设计函数 getter 和 setter 然后让类 C 通过类 A 的 getter 和 setter 读取类 A 对象的 private 和 protected 变量呢?
friend is for when you don't want to use getters/setters/internals to expose everyone, but just to a single class. So it's a tool for encapsulation.
For example, if you provided a public getSecret in MyClass, everyone could have access to that private variable even if they shouldn't know about it. This breaks encapsulation. friend is there to fix this problem, so that only those classes that need to know about secret have access to it.
所以说其实 friend class 使用的好的话,也相当于保护了封装性。
提示
将 friend class 比喻为你的朋友:
It's like giving your physical friend a key to your house but you(instance of class) don't know what they will do with it"
friend class 设计其实是单一责任原则:
So a friend class has unlimited access to all internals of the class it's friends with. This in unfortunate, but the key (no pun intended) here is to keep classes as small as possible so that this doesn't become a problem, which also would be according to the Single Responsibility Principle.