C ++:有没有办法限制对某些类的某些方法的访问,而不暴露其他私有成员? [英] C++: Is there a way to limit access to certain methods to certain classes without exposing other private members?
问题描述
我有一个类有受保护的方法Zig :: punt(),我只想要它可以访问的类鳄梨。在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?
提前感谢任何想法!
推荐答案
这是一个丑陋但有效的方法:
Here's an ugly yet working trick:
class AvocadoFriender {
protected:
virtual void punt() = 0;
friend class Avocado;
}
class Zig : public AvocadoFriender {
...
protected:
void punt();
}
基本上你添加一个mixin类,只暴露界面的一部分,想要鳄梨。我们利用这样一个事实,通过继承一个与Avocado友好的类,除了最初暴露的内容之外,你不会暴露任何东西。
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.
这篇关于C ++:有没有办法限制对某些类的某些方法的访问,而不暴露其他私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!