我试图在两个类(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/