author:
- luixiao1223
title: ‘若所有参数需要类型转换,请采用non-member函数’
tips
- 令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的时候应该尽量避免