我无法获得好友会员功能以实际访问私人会员

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

本文关键字:访问 功能 好友      更新时间:2023-10-16

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

我已经在这个网站和其他一些网站中做了一些研究,我实际上找到了一些有效的代码,但我真的看不出我试图实现的逻辑与it: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&( 能够访问类 A 的私有成员"a",但是当我尝试编译我的代码时,它会产生以下错误:

友谊继承.cpp(10(:错误 C2027:使用未定义的类型"B">

友谊继承.cpp(5(:注:见"B"声明

友谊继承.cpp(21(:错误 C2248:"A::a":无法访问私有 在"A"类中声明的成员

友谊继承.cpp(12(:注:见"A::a"声明

友谊继承.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;
}