c++ - friend 关键字(类/函数)如何打破 C++ 中的封装?

标签 c++ function friend

有些程序员说,“友元函数破坏了 C++ 中的封装”。也有程序员说“友元函数不会破坏封装,而是自然地扩展了封装屏障”

这是什么意思?..

如果友元函数破坏了 C++ 中的封装,那该怎么办??

最佳答案

引自 C++ FAQ我认为这很好地描述了 friend 和封装的情况。

No! If they're used properly, they enhance encapsulation.

You often need to split a class in half when the two halves will have different numbers of instances or different lifetimes. In these cases, the two halves usually need direct access to each other (the two halves used to be in the same class, so you haven't increased the amount of code that needs direct access to a data structure; you've simply reshuffled the code into two classes instead of one). The safest way to implement this is to make the two halves friends of each other.

If you use friends like just described, you'll keep private things private. People who don't understand this often make naive efforts to avoid using friendship in situations like the above, and often they actually destroy encapsulation. They either use public data (grotesque!), or they make the data accessible between the halves via public get() and set() member functions. Having a public get() and set() member function for a private datum is OK only when the private datum "makes sense" from outside the class (from a user's perspective). In many cases, these get()/set() member functions are almost as bad as public data: they hide (only) the name of the private datum, but they don't hide the existence of the private datum.

关于c++ - friend 关键字(类/函数)如何打破 C++ 中的封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1093618/

相关文章:

c++ - 继承CTAD构造函数

c++ - 函数中定义的 std::string 保留其先前的值?

ios - Swift 中的单行函数

c++ - C++ 中的内部类会自动成为 friend 吗?

c++ - 限制类的模板 friend

c++ - 程序完成后强制停止播放MP3文件

function - 这两个函数调用约定有什么区别?

c++ - 将函数指针作为参数从 C 代码传递到 C++ 库

c++ - 如何为模板类中定义的类定义 friend

c++ - 什么是 __declspec,我什么时候需要使用它?