友元函数访问权限小细节

今天在做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;
}

顺利通过!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值