我一直在为我的编程类(class)做练习,我现在参加的特别练习是关于友元函数/方法/类的。我遇到的问题是我的 friend 功能似乎没有完成它的工作;在我尝试访问友元函数应该有权访问的变量时,我的代码出现“[variable name] is private within this context”错误。
这里是头文件中的类定义(为了节省空间,我删掉了不需要的东西)。
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
类私有(private)的,这是为什么你会收到错误。仅仅因为您的函数是Statistics
的 friend ,并不意味着它们可以访问Statistics
的成员 的内部结构。他们只能访问 Statistics
的内部。事实上,Statistics
本身甚至无法访问 PersonalData
的内部结构,所以它的 friend 们当然也没有。
有几种方法可以解决这个问题。您可以将 PersonalData
的成员公开 - 但这不是一个好主意,因为您会减少封装。你可以让你的函数也成为 PersonalData
的 friend ——你最终可能会得到一个奇怪的友元图(比如 C++ 类的 Facebook!)。或者,您可以为 PersonalData
提供一些允许其他人查看其私有(private)数据的公共(public)接口(interface)。
正如@Angew 在评论中指出的,当 Statistics
的友元被命名为 equalFunctionFriend
时,你的函数被命名为 equalFunctionFriend
- 你有一个丢失的字母。这也会导致这个问题。
关于C++ 友元函数不起作用,在此上下文错误中私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13673300/