C++友元函数不起作用,在此上下文中是私有的错误
C++ friend function not working, private within this context error
我一直在为我的编程课程做一个练习,我现在正在学习的特定练习是关于朋友函数/方法/类的。我遇到的问题是我的好友功能似乎没有完成它的工作;我在我的代码周围收到"[变量名称]在此上下文中是私有的"错误,我正在尝试访问友元函数应该有权访问的变量。
这是头文件中的类定义(我删除了不必要的东西以节省空间)。
class Statistics {
private: // The personal data.
PersonalData person;
public:
Statistics();
Statistics(float weightKG, float heightM, char gender);
Statistics(PersonalData person);
virtual ~Statistics();
...
friend bool equalFunctionFriend(Statistics statOne, Statistics statTwo);
friend string trueOrFalseFriend(bool value);
};
这是出现错误的方法。
bool equalFuntionFriend(Statistics statOne, Statistics statTwo)
{
// Check the height.
if (statOne.person.heightM != statTwo.person.heightM)
return false;
// Check the weight.
if (statOne.person.weightKG != statTwo.person.weightKG)
return false;
// Check the gender.
if (statOne.person.gender != statTwo.person.gender)
return false;
// If the function hasn't returned false til now then all is well.
return true;
}
所以,我的问题是:我做错了什么?
编辑:问题已由Angew解决。似乎这只是一个错字...很傻的我!
我猜heightM
、weightKG
和gender
是你的PersonalData
类私有的,这就是你收到错误的原因。仅仅因为你的函数是Statistics
的朋友,并不意味着它们可以访问Statistics
成员的内部。他们只能访问Statistics
的内部结构。事实上,Statistics
本身甚至无法访问PersonalData
的内部结构,所以它的朋友当然不会。
有几种方法可以解决这个问题。你可以公开PersonalData
的成员 - 但这不是一个好主意,因为你会减少封装。你可以让你的函数也成为PersonalData
的朋友 - 你最终可能会得到一个奇怪的友谊图(比如C++类的Facebook!)。或者你可以给PersonalData
一些公共接口,允许其他人偷看其私人数据。
正如@Angew在评论中指出的那样,当Statistics
的朋友被命名为equalFunctionFriend
时,您的函数被命名为equalFuntionFriend
- 您缺少一个字母。这也会导致此问题。
相关文章:
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 错误"Could not find Boost"(缺少:上下文标头)
- DCMTK 了解"DIMSE 没有有效的演示上下文 ID"错误
- MSVC 在不知道类型的情况下评估上下文(和错误)
- 关于 GetDIBits 和设备上下文的奇怪错误
- 自定义删除器,用于shared_ptr<>给出"无上下文错误"
- Linux/QT-错误创建SSL上下文(错误:140A90C4 ..)
- 分段错误将文本呈现到开罗上下文
- 在spirit parser Action中,在上下文参数上编译boost :: bind(成员函数)上的错误
- OpenGL 上下文创建期间未记录的错误
- 如何修复C#应用程序中调用C++DLL函数时的上下文加载错误
- 带有 QT 错误的 OpenGL:ASSERT:"QOpenGLFunctions::isInitialized(d_ptr)" 。无法创建 OpenGL 上下文
- 当任何子线程导致错误时,上下文切换到主线程
- 带有模板的矢量在打印上下文时在瓦尔格林德中给出错误
- C++上下文错误
- 渲染自定义模型时出现c++Directx 11设备上下文错误
- 此上下文标记中的错误可能会标记错误的位置
- 类声明错误:上下文信息不足,无法确定类型
- 激活上下文生成失败.VC运行时错误
- VS 2013 单元测试不起作用 =设置执行上下文时出现>错误