Effective C++(若所有参数需要类型转换,请采用non-member函数)


author:

  • luixiao1223
    title: ‘若所有参数需要类型转换,请采用non-member函数’

tips

  1. 令class支持隐式类型转换是一件糟糕的事情。

例子

class Rational{
    const Rational operator* (const Rational& rhs) const;
};

如果这样用可以

Rational oneEnglish(1, 8);
Rational oneHalf(1, 2);
Rational result = oneHalf * oneEnglish;
result = result * oneEnglish // all good

problems

result = oneHalf * 2; // good;
result = 2 * oneHalf; // Error;

解决

// This is not a member function.
const Rational operator*(const Rational& lhs,
                         const Rational& rhs)
{
    return Rational (lhs.numerator() * rhs.numerator(),
                     lhs.denominator() * rhs.numerator());
}

Rational oneFourth(1, 4);
Rational result;

result oneFourth * 2; // Right
result = 2 * oneFourth; // 通过编译了。

是否该把上面的函数加上friend属性呢?答案是否定的。因为上面的代码不需要友元的属性就可以运行。因此为了封装性,不应该这么做。

可以避免friend的时候应该尽量避免

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值