好友功能

发布于 2024-11-17 17:33:20 字数 260 浏览 2 评论 0原文

只是一个关于友元函数的使用,或者更确切地说它们的有用性的简单问题。基本上..

它们有什么用?如果您正确设计了类,那么真的需要友元函数吗?在什么情况下您想使用或不使用它们?有人告诉我它们增强了封装性,但根据我的经验,在我编码的 7 年里我只使用了一个友元函数。在进一步检查和重构我的代码之后,我意识到我什至不需要使用它。看起来它们有点违反封装性,而不是增强它。这可能是由于我缺乏该领域的知识。

太棒了;友元函数有什么用处,什么时候应该/不应该使用它们,以及它们如何增强封装性?

Just a simple question about the use of friend functions, or rather their usefulness. Basically..

How are they useful? If you've properly designed your classes, would there really be a need for friend functions? What are cases where you'd want to use or not use them? I'm told that they enhance encapsulation, but from my experiences, I've only used one friend function in the 7 years I've been coding. After further examination and refactoring of my code, I realized I didn't even need to use it. It seems like they somewhat violate encapsulation, rather than ehancing it. This is probably due to my lack of knowledge in the area.

tldr; What is so useful about friend functions, when should/should not they be used, and how do they enhance encapsulation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

Hello爱情风 2024-11-24 17:33:20

任何告诉你友元函数增强封装性的人都是完全错误的,他们是完全相反的。它们在真正的 OOP 世界中确实没有地位。

然而,生活很少是完美的,有时您需要从框架内的其他类调用受保护的方法,而不将它们暴露给外部。 C# 和 Java 非常优雅地解决了这个问题:它们有一个 internal 修饰符(含义略有不同),但在 C++ 中你拥有的只是 friend

如果您确实已经编程了 7 年而从未需要此构造,那么您要么将类中的每个方法和变量设为 public,要么根本不使用类。

Whoever told you friend functions enhance encapsulation is plain wrong, they're the exact opposite. They truly have no place in a truly OOP world.

However, life is rarely perfect, and at times you'll need to call protected methods from other classes within your framework, without exposing them to the outside. C# and Java solved this problem very elegantly: they have an internal modifier (with slightly different meanings), but in C++ all you have is friend.

If you truly have been programming for 7 years without ever needing this construct, then you either make every method and variable in your class public or you don't use classes at all.

青萝楚歌 2024-11-24 17:33:20

我能想到的一种场景是多个项目共享代码。您的 B 类需要访问 A 类中由单独组拥有的私有成员。如果您无法破坏该类的现有合同,您可以添加一个朋友方法,该方法可以执行您需要的操作,而不会破坏其他组的任何内容。

当然,现在使用 .NET 4,我们能够向类添加动态方法,这完全消除了我的情况。

One scenario I can think of is when multiple projects share code. Your class B needs to access private members in class A which is owned by a separate group. If you cannot break the existing contract of that class you could add a friend method which does what you need it to without breaking anything for the other group.

Of course now with .NET 4 we have the ability to add dynamic methods to classes which eliminates my scenario completely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文