friend关键字(类/函数)如何破坏C ++中的封装? [英] How does the friend keyword (Class/Function) break encapsulation in C++?

查看:172
本文介绍了friend关键字(类/函数)如何破坏C ++中的封装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些程序员说,一个朋友函数打破了C ++中的封装。一些程序员也说,朋友的功能不会打破封装,而是自然延伸封装的障碍

Some programmer said that, "a friend function break the encapsulation in C++". and some programmer also said, "Friend functions do not break encapsulation; instead they naturally extend the encapsulation barrier"

这是什么意思?

如果朋友函数打破了C ++中的封装,那么如何

If a friend function breaks the encapsulation in C++ then how??

推荐答案

a href =http://www.parashift.com/c++-faq-lite/friends.html#faq-14.2> C ++常见问题,我认为它描述的情况与朋友和封装很好。 p>

Quote from C++ FAQ which I think describes the situation with friend and encapsulation very well.


否!

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

你通常需要将一个类分成两半,当两个半框有
个不同的实例数时,
不同的生命周期。在这些情况下,
两个半部分通常需要直接
访问对方(两个半部分
过去是在同一个类,所以你
没有增加的金额的代码
需要直接访问数据
结构;你只需将
代码重新整理为两个类,而不是
one)。实现这个
的最安全的方法是让两个朋友的
彼此。

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.

如果你使用刚才描述的朋友,我们保持私人东西
私人。那些不理解
的人通常会在上面的例子中使用友谊来避免
,通常他们实际上是
破坏封装。他们使用
公共数据(怪诞!),或者他们通过public get()和set()member
函数使
之间的数据可以在两半
之间访问。只有当私人
数据从
类外部有意义时,才有一个私人
数据的public get()和
set()成员函数用户的观点)。在
很多情况下,这些get()/ set()成员
函数几乎和public
数据一样糟糕:它们只隐藏
私人数据的名称,但它们不隐藏私人数据的
存在。

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.

这篇关于friend关键字(类/函数)如何破坏C ++中的封装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆