授予没有朋友的私有构造函数访问权限? [英] Grant access to private constructor without friends?

查看:53
本文介绍了授予没有朋友的私有构造函数访问权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写某些代码,遇到的情况与此类似:

I am working on some code, where I encountered a situation similar to this one:

struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

我希望拥有 Bar 不是 Foo friend ,因为除了 Foo 的构造函数 Bar 不需要访问任何 Foo 的私有方法(因此不应具有访问权限)。有没有办法只允许 Bar 创建 Foo s而又不使其成为朋友?

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS :意识到问题可能不是100%明确的。我不介意是否通过朋友访问,只是所有 Bar 都可以访问所有私有方法的事实困扰着我(通常< friends ),这就是我要避免的事情。幸运的是,到目前为止,给出的答案都没有那个糟糕的表述问题。

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

推荐答案

这正是律师-客户惯用语适用于:

struct Bar;

struct Foo {
    friend struct FooAttorney;
private:
    Foo(){}
    void f(){}
    void g(){}
};

class FooAttorney {
  static Foo* makeFoo() { return new Foo; }
  friend struct Bar;
};

struct Bar {
   Foo* f;
   Bar()  { f = FooAttorney::makeFoo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

在模仿生活的代码中,班级宣布了一名律师,将调解愿意与所选方共享的秘密。

In a code imitates life fashion, the class declares an attorney that will mediate the secrets it's willing to share with the selected parties.

这篇关于授予没有朋友的私有构造函数访问权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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