【发布时间】:2012-11-20 07:57:18
【问题描述】:
我一直在为我的编程课程做一个练习,而我现在正在练习的是关于朋友函数/方法/类的练习。我遇到的问题是我的朋友功能似乎没有做它的工作;我在代码中遇到“[变量名] 在此上下文中是私有的”错误,我试图访问友元函数应该有权访问的变量。
这是头文件中的类定义(我删掉了不必要的东西以节省空间)。
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 解决。看来这只是一个错字……我太傻了!
【问题讨论】:
-
你的函数也是
PersonalData的朋友吗? -
第二个代码示例中有错字,缺少
c(只是equalFuntionFriend)。如果这是从您的代码中实际复制和粘贴,那就是问题所在。 -
尽可能避免使用
if语句(它们的计算量很大,尽管在这里它们可能会被优化掉)。实际上,您可以在这里只使用一个 return 语句:return statOne.person.heightM == statTwo.person.heightM && statOne.person.weightKG == statTwo.person.weightKG && statOne.person.gender == statTwo.person.gender;(可能会被分成 3 行以使其更易于人类阅读)
标签: c++ function private friend