C++:使用友元类而不是编写 getter/setter 的不好做法?
我有两个班级,它们在一方面紧密合作。它们都使用彼此的功能,这些功能只能由它们使用,而不能由任何其他类使用。
- 如果我让这两个类成为朋友,这样它们就可以直接访问和操作彼此的成员变量,而不使用任何 getter / setter 函数,这是一种不好的做法吗?
I have two classes which in one aspect work together tightly. They both use functionality of each other that should be only used by them and not by any other class.
- Is it bad practice if I make those two classes friends so they can directly access and manipulate member variables of each other, without using any getter / setter functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getter、setter 和友元类都减少了封装并增加了耦合。至少友谊将减少的封装限制为需要额外访问的显式指定的类。事实上,这两个类现在紧密耦合不一定是坏事,它们可以被视为整体设计的单个单元。
Both getters and setters and friend classes reduce encapsulation and increase coupling. At least friendship restricts the reduced encapsulation to the explicitly specified classes that need the extra access. The fact that the two classes are now tightly coupled need not be a bad thing, they can be considered a single unit of the overall design.
不,一点也不。这是一件很常见的事情,实际上,你有一个类,但它必须在生命周期和其他实现方面分成两个类。在这种情况下,朋友班绝对是最佳选择。
如果更改一个类的实现意味着您必须更改另一个类的实现,那么这绝对适用。特别是如果您需要这两者之间的界面元素不适用于公开。
朋友类的存在是有原因的。
No, not at all. It's a common thing that effectively, you have one class, but it has to be split up into two for lifetime and other implementation things. In this case, friend classes are definitely the way to go.
If changing the implementation of one class means that you'd have to change the implementation of the other, then this is definitely applicable. Especially if you need interface elements between these two that don't apply to being public.
Friend classes exist for a reason.