班级的朋友是无法接近的

Friend of the class is inaccesible

提问人:Aqib Naeem 提问时间:7/4/2020 最后编辑:James ZAqib Naeem 更新时间:7/4/2020 访问量:40

问:

我正在尝试编写一个非常简单的代码作为实践。问题是当我将一个类的成员函数与另一个类交友时,它说不可访问,但是当我将整个类声明为另一个类的朋友时,它工作正常。

#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;
}
C++ OOP 友类

评论

0赞 Rohan Bari 7/4/2020
如果将期望从该代码中获得的内容添加为输出,则最好了解要使用的逻辑。

答:

0赞 gkhaos 7/4/2020 #1

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

定义函数时不需要实现该函数,并在此处引起问题:在定义时无法实现,因为尚未定义。但是在定义后实现它完全没有问题。setnum1(int, gpa2&)class gpa1setnum1class gpa2gpa2

因此,通过一些小的改动: Godbolt 示例

#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;
}