class 的好友无法访问

Friend of the class is inaccesible

我正在尝试编写一个非常简单的代码作为练习。问题是当我将一个 class 的成员函数设为另一个 class 的成员函数时,它说无法访问但是当我将整个 class 声明为另一个 class 的成员函数时,它工作正常。

#include <iostream>
using namespace std;
class gpa2;
class gpa1 {
private:
    int no1;
    int no2;
public:
    void setnum1(int n1, gpa2&xp) {
        cout << " the friend member function is : " << xp.no4;
    }
    void setnum2(int n2) {
        no2 = n2;
        cout << "num2 is : " << no2 << endl;
    };
};

class gpa2 {
private:
    int no3;
    int no4;
    friend void gpa1::setnum1(int, gpa2&);
public:
    void setnum3(int n3) {
        no3 = n3;
        cout << "num3 is : " << no3 << endl;
    }
    void getnum4(int n4) {
        cout << "num4 is :  " << n4 << endl;
    }
};

int main() {
    gpa1 g1;
    gpa2 g2;
    g1.setnum1(15, g2);
    g1.setnum2(30);
    g2.setnum3(45);
    g2.getnum4(50);
    return 0;
}

xp.no4 不可访问,因为 setnum1gpa1 的成员函数,而不是 gpa2

函数setnum1(int, gpa2&)定义的时候不需要实现,这里会出现问题:定义class gpa1setnum1无法实现,因为class gpa2 尚未定义。但是在定义 gpa2 之后实现它完全没有问题。

因此,有一些小的变化:Godbolt example

#include <iostream>
using namespace std;

// forward declaration
class gpa2;

class gpa1 {
private:
    int no1;
    int no2;
public:
    void setnum1(int n1, gpa2& xp);
    void setnum2(int n2) {
        no2 = n2;
        cout << "num2 is : " << no2 << endl;
    };
};

class gpa2 {
private:
    int no3;
    int no4;
    friend void setnum1(int, gpa2&);
public:
    void setnum3(int n3) {
        no3 = n3;
        cout << "num3 is : " << no3 << endl;
    }
    void getnum4(int n4) {
        cout << "num4 is :  " << n4 << endl;
    }

    int num4() { return no4; } // added accesibility to no4
};

// implementation of setnum1
void gpa1::setnum1(int n1, gpa2& xp)  {
    cout << " the friend member function is : " << xp.num4();
}



int main() {
    gpa1 g1;
    gpa2 g2;
    g1.setnum1(15, g2);
    g1.setnum2(30);
    g2.setnum3(45);
    g2.getnum4(50);
    return 0;
}