C++友元函数不起作用,在此上下文中是私有的错误

C++ friend function not working, private within this context error

本文关键字:错误 上下文 函数 友元 不起作用 C++      更新时间:2023-10-16

我一直在为我的编程课程做一个练习,我现在正在学习的特定练习是关于朋友函数/方法/类的。我遇到的问题是我的好友功能似乎没有完成它的工作;我在我的代码周围收到"[变量名称]在此上下文中是私有的"错误,我正在尝试访问友元函数应该有权访问的变量。

这是头文件中的类定义(我删除了不必要的东西以节省空间)。

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解决。似乎这只是一个错字...很傻的我!

我猜heightMweightKGgender是你的PersonalData类私有的,这就是你收到错误的原因。仅仅因为你的函数是Statistics的朋友,并不意味着它们可以访问Statistics成员的内部。他们只能访问Statistics的内部结构。事实上,Statistics本身甚至无法访问PersonalData的内部结构,所以它的朋友当然不会。

有几种方法可以解决这个问题。你可以公开PersonalData的成员 - 但这不是一个好主意,因为你会减少封装。你可以让你的函数也成为PersonalData的朋友 - 你最终可能会得到一个奇怪的友谊图(比如C++类的Facebook!)。或者你可以给PersonalData一些公共接口,允许其他人偷看其私人数据。

正如@Angew在评论中指出的那样,当Statistics的朋友被命名为equalFunctionFriend时,您的函数被命名为equalFuntionFriend- 您缺少一个字母。这也会导致此问题。