C++:有没有办法限制对某些类的某些方法的访问而不暴露其他私有成员?
我有一个带有受保护方法 Zig::punt() 的类,我只希望“Avocado”类可以访问它。在 C++ 中,您通常会使用“friend Avocado”说明符来执行此操作,但这将导致“Avocado”类可以访问所有其他变量;我不想要这个,因为这会破坏封装。
我想要的东西是不可能的吗,还是已经存在一个我可以用来实现我想要的东西的晦涩技巧?或者可能可以实现相同目标的替代类设计模式?
预先感谢您的任何想法!
I have a class with a protected method Zig::punt() and I only want it to be accessible to the class "Avocado". In C++, you'll normally do this using the "friend Avocado" specifier, but this will cause all of the other variables to become accessible to "Avocado" class; I don't want this because this breaks encapsulation.
Is what I want impossible, or does there already exist an obscure trick out there that I can use to achieve what I want? Or possibly alternative class design patterns that'll achieve the same thing?
Thanks in advance for any ideas!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个丑陋但有效的技巧:
基本上,您添加一个 mixin 类,该类仅向 Avocado 公开您想要的接口部分。我们利用了这样一个事实:通过继承与 Avocado 友好的类,除了最初暴露的内容之外,您不会再暴露任何其他内容。
Here's an ugly yet working trick:
Basically you add a mixin class that exposes only the part of the interface that you want to Avocado. We take advantage of the fact that by inheriting a class that is befriended to Avocado you don't expose anything more except what was exposed originally.
我个人喜欢
Key
模式。现在:
我真的很喜欢这个解决方案,因为:
WannaBeFriend
的子类:它只需要公开一个protected: static const WannaBeFriend& 。 Key();
(可能适用,也可能不适用)当然,编译器很可能会优化此引用的传递,因为它没有任何目的,因此它不会破坏设计,也不会添加不必要的内容临时工:)
I personally like the
Key
pattern.And now:
I really like this solution because:
WannaBeFriend
: it only needs exposing aprotected: static const WannaBeFriend& Key();
(may or may not apply)And of course, it's very likely that the compiler will optimize the passing of this reference since it does not serve any purpose, so it does not corrupt the design nor add unnecessary temporaries :)
您可以向 Zig 类添加代理
You can add a proxy to the Zig class