c++ - Friend c++ 不与私有(private)成员一起工作

标签 c++ friend

我试图在两个类(class)之间建立 friend 关系。以下是示例:

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 中,而不是在类 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;
}

关于c++ - Friend c++ 不与私有(private)成员一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50349568/

相关文章:

c++ - 如何更改makefile中g++的版本

c++ - 需要左值作为递增操作数 (2)

c++ - Visual Studio C++ 和 Android 模拟器?

c++ - 成员(member)功能 friend

2行之间的PHP friend 关系?

c++ - `noexcept`的正确使用

c++ - 函数原型(prototype)中的 const 参数

c++ - 在类模板中没有定义参数的情况下调用 friend 模板函数

c++ - 模板和重载 istream

c++ - 其他模板可用的功能?