从友元类的友元函数访问私有成员

时间:2021-05-17 20:33:10

标签: c++ class

我正在尝试从友元函数访问类的私有成员,但我不断收到关于 xB 的私有类的错误。

我知道一个特定的解决方案可能只是 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;
}

0 个答案:

没有答案