文章目录
令class支持隐式类型转换通常是个糟糕的主意
只有当参数被列于参数列内,这个参数才是隐式类型转换的合格参与者。
下面的非成员函数可以实现混合式算数运算:
class Rational{
... //不包括operator*
};
const Rational operator*(const Rational& lhs,const Rational& rhs)
{
return Rational(lhs.numerator()*rhs.numerator(),lhs.denominator()*rhs.denominator());
}
Rational oneFourth(1,4);
Rational result;
result=oneFourth*2; //ok
result=2*oneFourth; //这个也可以,如果在non-explicit构造函数,而且此函数是Rational内的成员函数
的情况下,这个是不允许的
现在我们来讨论为什么在上述情况下,两种方式都可隐式转换,因为operator* 函数是non-member,则数字2无论在oneFourth左边还是右边都可以在operator* 函数内隐式转换成:
const Rational temp(2);
但是如果operator* 函数是Rational类的成员函数,则只有result=oneFourth* 2可以通过编译,因为oneFourth可以调用operator* 函数:
result=oneFourth.operator*(2)
这里2也可以隐式转换成Rational类型。
但是result=2* oneFourth因为2不能调用operator* 函数,因此转换不成功。
总结——135
如果你需要为某个函数的所有参数(包括被this指针所指的那个隐喻参数)进行类型转换,那么这个函数必须是个non-member。