Friend c++ 不与私有成员一起工作

Friend c++ not working with private members

我试图在两个 类 之间建立朋友关系。以下是示例:

class A
{
public:
  int b;
private:
  friend class B;
  int a;
};

class B
{
  public:
  A abc;
};

int main ()
{
  B b;
  b.abc.b = -1;
  b.abc.a = 0;
  return 0;
}

编译时出现如下错误:

test.cpp: In function ‘int main()’: test.cpp:20:9: error: ‘int A::a’ is private within this context b.abc.a = 0; ^ test.cpp:7:7: note: declared private here int a; ^

如有任何帮助,我们将不胜感激。

friend 允许 code 访问否则无法访问的名称。但是,访问成员 a 的代码在 main 中,而不是在 class B 中,因此它没有特殊的访问权限。

你需要这样的东西:

class B
{
  public:
  A abc;

  void set_abc_a(int i) { abc.a = i; }
};

int main ()
{
  B b;
  b.abc.b = -1;
  b.set_abc_a(0);
  return 0;
}