今天在做c++primer plus 上的题目的时候,编译器总是提示[Error] ‘Lbs_per_stn’ was not declared in this scope。
private:
enum {Lbs_per_stn = 14};
我的Lbs_per_stn定义在了私有成员里的enum,即声明了一个常量Lbs_per_stn,其值为14,(事实上Lbs_per_stn只是一个符号,编译器将用14代替之)
接着我在成员函数和友元函数中都使用了该常量。
成员函数中
Stonewt::Stonewt(int stn,double lbs)
{
mode=Stonewt::double_lbs;
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn +lbs;
}
友元函数中
Stonewt operator+(const Stonewt &m1,const Stonewt &m2 )
{
Stonewt M;
M.pounds=m1.pounds + m2.pounds;
M.stone=int(M.pounds)/ Lbs_per_stn;
M.pds_left=int (M.pounds) % Lbs_per_stn + M.pounds- int(M.pounds);
return M;
}
结果编译器只在友元函数中报错了,为什么??原来,友元函数不能直接访问类的成员,只能访问对象成员!!所以我将上面友元函数的代码改成了:
Stonewt operator+(const Stonewt &m1,const Stonewt &m2 )
{
Stonewt M;
M.pounds=m1.pounds + m2.pounds;
M.stone=int(M.pounds)/ m1.Lbs_per_stn;
M.pds_left=int (M.pounds) % m1.Lbs_per_stn + M.pounds- int(M.pounds);
return M;
}
顺利通过!