我无法获得朋友成员功能来实际能够访问私人成员

时间:2019-08-19 17:40:38

标签: c++ class definition friend

我正在阅读有关c ++中的友谊的信息(我以为我实际上理解了它),但是当我在某些类中使用源代码进行尝试时,我只是无法成功。我希望能够了解为什么它不起作用。

我已经在该网站和其他网站中进行了一些研究,实际上我发现了一些有效的代码,但是我真的看不到我试图实现的逻辑与它有何不同:{{ 3}}

struct B;

struct A{
    A(int _a): a(_a){}
    friend void B::showA(A&);
    private:
    int a;
};

struct B{
    void showA(A&);
};

void B::showA(A& _param){
    cout << _param.a;
}

我希望void B :: showA(A&)函数能够访问类A的私有成员“ a”,但是当我尝试编译我的代码时,它会产生以下错误:

friendshipninheritance.cpp(10):错误C2027:使用未定义的类型'B'

friendshipninheritance.cpp(5):注意:请参见“ B”声明

friendshipninheritance.cpp(21):错误C2248:'A :: a':无法访问私有 在“ A”类中声明的成员

friendshipninheritance.cpp(12):注意:请参见“ A :: a”的声明

friendshipninheritance.cpp(7):注意:请参阅“ A”声明

2 个答案:

答案 0 :(得分:4)

只需重新排序声明即可。

struct A;

struct B{
    void showA(A&);
};


struct A{
    A(int _a): a(_a){}
    friend void B::showA(A&);
    private:
    int a;
};

void B::showA(A& _param){
    cout << _param.a;
}

结构A必须知道结构B的成员的名称。也就是说,B的定义必须在A的定义之前,以便知道名称showA

答案 1 :(得分:2)

根据经验,应该从头解决编译器错误。通常,一个错误会产生更多的错误,在这种情况下也是如此。

您的friend声明被忽略,因为编译器尚不知道B是什么,以及它是否具有称为showA的任何函数。这会导致所有其他错误。

您可以更改声明的顺序以使其起作用:

struct A;

struct B{
    void showA(A&);
};

struct A{
    A(int _a): a(_a){}
    friend void B::showA(A&);
    private:
    int a;
};

void B::showA(A& _param){
    cout << _param.a;
}
相关问题