允许类访问单个私有成员
我有一个类 A,它有一个名为 a() 的私有方法。我还有一个类 B 需要访问 a() (但只有 B 应该有权访问 a(),这就是为什么 a() 是私有的)。我现在可以使用朋友说明符,但这将使 A 的其他私有方法(我们称它们为 b() 和 c())也可供 B 使用,我不希望出现这种行为。
有没有办法让 B 只能访问 A 的 a() ?
I have a class A which has a private method called a(). I have also a class B which needs to access a() (but just B should have access to a(), thats why a() is private). I could now use a friend specifier but that would make other private methods of A (lets call them b() and c()) also available to B and I dont want that behaviour.
Is there a way to make just a() of A accessable to B?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有一种方法 - 如果你的类有一个公共模板函数:
我必须承认我从 GotW 那里偷了这个......
There is a way -- if your class has a public template function:
I must confess I stole this from GotW...
不,没有,但是当您指定精确的类时,只有 B 可以访问 A 的私有成员。
您只需要注意调用什么方法即可。
由于好友关系不是继承的,所以不必担心 B 可能存在的子类。
No there's not, but as you specify the precise class, just B could access A's private members.
You just have to take care of what method are called.
As friend relationship are not inherited, you don't have to worry about B's possible subclasses.
这可以通过一些“扭转”来完成。
只需将 A 类中的方法 a() 分解到以 B 作为友元类的父类中,然后让 A 继承它即可。这将使 a() 成为 A 中的一个方法,但它是其父级的朋友 B 可以访问的唯一私有方法。
这里有一个非常简单的代码来澄清我所说的内容:
希望它有所帮助!
This could be done with some "twist".
Just factor out method a() from A class into a parent class that has B as a friend class, then let A inherit it. this will leave a() as being a method in A, but the only private method accessible by its parent's friend B.
here is a very simple code to clarify what I've said:
hope it helps !
是的,我有一个简单的方法。让 B 有一个指针 A::a(),如下所示:
Yes, I have an easy way. Let B have a pointer of A::a(), like this: