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

i can't get a friend member function to actually be able to access private members

我正在阅读有关 c++ 中的友谊(我以为我真的理解它),但是当我转到源代码在一些 classes 中尝试它时,我只是无法理解它去。我希望能够理解为什么它不起作用。

我已经在这个网站和其他一些网站上做了一些研究,我实际上找到了一些有效的代码,但我真的看不出我试图实现的逻辑与它有何不同: https://www.geeksforgeeks.org/friend-class-function-cpp/

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&) 能够访问 class A 的私有成员 "a",但是当我尝试编译我的代码时,它会产生这些错误:

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

friendshipninheritance.cpp(5): 注意:参见 'B'

的声明

friendshipninheritance.cpp(21): error C2248: 'A::a': 无法访问私有 在 class 'A'

中声明的成员

friendshipninheritance.cpp(12): 注意:参见 'A::a'

的声明

friendshipninheritance.cpp(7): 注意:参见 'A'

的声明

只需重新排序声明即可。

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

根据经验,您应该从头开始解决编译器错误。通常,一个错误会引发更多错误,在这种情况下也不例外。

您的 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;
}