gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:59:11 25 4
gpt4 key购买 nike

有些程序员说,“友元函数破坏了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com