让内部类成为 C++ 中的朋友

发布于 2024-11-15 10:56:16 字数 292 浏览 4 评论 0原文

我想让一个内部类成为一个不相关类的友元,但这似乎不起作用(至少在 gcc 4.1.2 中):

class A {
    int i;
    friend class B; // fine
    friend class B::C; // not allowed?
};

class B {
    int geti(A* ap) { return ap->i; }

    class C {
        int geti(A* ap) { return ap->i; }
    };
};

I want to make an inner class a friend of an unrelated class but this doesn't seem to work (at least in gcc 4.1.2):

class A {
    int i;
    friend class B; // fine
    friend class B::C; // not allowed?
};

class B {
    int geti(A* ap) { return ap->i; }

    class C {
        int geti(A* ap) { return ap->i; }
    };
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2024-11-22 10:56:16

在使用它之前,您必须声明B::C。以下可能有效。

更新:忽略所要求的可用演示,这里有一种可以工作的构造方法(减去成员函数的定义),但请记住,一切都是私有的。

class A;

class B
{
  int geti(A * ap);

public:
  class C
  {
    int geti(A * ap);
  };
};

class A
{
  friend class B;    // fine
  friend class B::C; // fine too
  int i;
};

然后在别处定义 getter 函数:

int B::geti(A * ap) { ... }
int B::C::geti(A * ap) { ... }

替代方案:前向声明嵌套类 B::C 并保存一个外部定义:

class A;

class B
{
  int geti(const A * ap) const; // we cannot use A yet!

public:
  class C;
};

class A
{
  friend class B;    // fine
  friend class B::C; // fine too
  int i;
};

int B::geti(const A * ap) const { return ap->i; }

class B::C
{
  inline int geti(const A * ap) const { return ap->i; }
};

You have to declare B::C before using it. The following might work.

Update: Ignoring a usable demonstration as requested, here's a way of structuring this (minus the definitions of member functions) that could work, but bear in mind that everything is private as it stands.

class A;

class B
{
  int geti(A * ap);

public:
  class C
  {
    int geti(A * ap);
  };
};

class A
{
  friend class B;    // fine
  friend class B::C; // fine too
  int i;
};

Then define the getter functions elsewhere:

int B::geti(A * ap) { ... }
int B::C::geti(A * ap) { ... }

Alternative: forward-declare the nested class B::C and save one external definition:

class A;

class B
{
  int geti(const A * ap) const; // we cannot use A yet!

public:
  class C;
};

class A
{
  friend class B;    // fine
  friend class B::C; // fine too
  int i;
};

int B::geti(const A * ap) const { return ap->i; }

class B::C
{
  inline int geti(const A * ap) const { return ap->i; }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文