我正在尝试从友元函数访问类的私有成员,但我不断收到关于 x
是 B
的私有类的错误。
我知道一个特定的解决方案可能只是 friend
内的函数 B
,但我想要一个更通用的解决方案,以防我需要在 A
中需要更多友元函数访问 B
但不想在 B 中显式 friend
它们。
#include <iostream>
using namespace std;
class B {
private:
int x = 10;
friend class A;
};
class A {
private:
B b;
public:
friend ostream& operator<< (ostream&, A&);
};
ostream& operator<< (ostream& out, A& a){
out << a.b.x << endl;
return out;
}
int main() {
A a;
cout << a;
return 0;
}