我无法获得好友会员功能以实际访问私人会员
i can't get a friend member function to actually be able to access private members
我正在阅读有关 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;
}
相关文章:
- 如何从其他功能C++访问参数?
- 如何使用 MPI 的远程内存访问 (RMA) 功能并行化数据聚合?
- 访问我以前可以访问的功能时出现分段错误
- 好友功能 - 成员无法访问
- 如何启用友元类的友元功能直接在C++中访问其私有成员
- 无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
- 无法访问公共功能? 没有指定成员?
- 好友功能仍无法访问私人会员
- 我无法获得好友会员功能以实际访问私人会员
- GPU设备函数如何访问主机功能中定义的对象
- 派生类中的成员字段别名(无访问器功能)
- 从C文件访问C 类成员功能
- 访问嵌套结构的数据成员并将结构传递到功能C
- 使用宏访问功能
- QT:类的访问功能,该功能使用构造函数外的GUI小部件
- 在其他源文件中没有通用的头文件访问功能
- 这是使用访问功能的好习惯
- 从C 访问功能环境中的LUA变量
- 如何在右键单击链接并从上下文菜单访问功能后获取链接的 DOM
- QObject信号和插槽未访问功能