朋友班有限访问 [英] friend class with limited access

查看:94
本文介绍了朋友班有限访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个类B类的朋友类。我想这样做,因为这些交互非常多,A需要改变B类的内部(我不想使用public公开)。但是我想确保它只能访问几个选定的功能,而不是所有的功能。



示例:

  class A 
{
};

class B
{
private:
void setState();
void setFlags();
朋友类A
};

我想要A能够访问setState,但不能设置setFlags ...是否有设计模式或在这种情况下,一个很好的方法,或者我在完全访问或完全访问的情况下离开了。



谢谢

解决方案

这取决于你的意思是一个很好的方式:)在comp.lang.c ++。主持我们有一个相同的问题前一段时间。你可能会看到它产生的讨论那里



IIRC,我们最终使用嵌套密钥的朋友方法。应用于您的示例,这将产生:

  class A 
{
};

class B
{
public:
class Key {
friend class A;
Key();
};

void setFlags(Key){setFlags();}

private:
void setState();
void setFlags();
};

想法是公共setFlags()必须用Key调用,只有朋友Key可以创建一个,因为它的ctor是私有的。


I want to make a class A friend class of class B. I want to do this as these interact very much and A needs to change internals of class B (which I dont want to expose using public). But I want to make sure it has access to only a few selected functions not all the functions.

Example:

class A
{
};

class B
{
private:
 void setState();
void setFlags();
friend class A
};

I want A to be able to access setState but not setFlags... Is there a design pattern or a nice way of doing this or am I left with giving full access or no access at all in this case.

Thanks

解决方案

It depends on what you mean by "a nice way" :) At comp.lang.c++.moderated we had the same question a while ago. You may see the discussion it generated there.

IIRC, we ended up using the "friend of a nested key" approach. Applied to your example, this would yield:

class A
{
};

class B
{
public:
     class Key{
         friend class A;
         Key();
     };

    void setFlags(Key){setFlags();}         

private:
  void setState();
  void setFlags();
};

The idea is that the public setFlags() must be called with a "Key", and only friends of Key can create one, as its ctor is private.

这篇关于朋友班有限访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆