Item24 若所有参数都需要类型转换,请为此采用non-member函数

让class支持隐式转换,通常是个糟糕的主意。但需要建立数值类型时,还是需要允许隐式转换。

注:无论何时,如果可以避免friend函数就该避免。

如果需要为某个函数的所有参数(包括被this指针所指的那个隐喻参数)进行类型转换,那么这个函数必须是非成员函数

如:

class Rational {
    ...
};

const Rational operator*(const Rational& lhs, const Rational& rhs)
{
    return Rational(lhs.numerator() * rhs.numerator(),
                    hls.denominator() * rhs.denominator());
}

上述,operator*为非成员函数,方便隐式类型,调用如下:

Rational oneFourth(1, 4);
Rational result;

result = oneFourth * 2;
result = 2 * onFourth;

猜你喜欢

转载自blog.csdn.net/u013015629/article/details/107437273