令classes支持隐式转换通常是个糟糕的主意。但是如果发生在数值类型上,比如设计一个class用来表现有理数,允许整数隐式转换为有理数似乎很是合理
class Rational
{
public:
Rational(int numerator = 0,int denominator = 1){}
int numerator()const{};
int denominator()const{};
const Rational operator* (const Rational &rhs)const{}
private:
};
int main()
{
Rational oneHalf(1,2);
Rational result = oneHalf * 2;
///Rational result2 = 2 * oneHalf;
///编译错误,因为并没有函数是2.operator*(oneHalf);
///编译器寻找non-member operator*也没有
}
改正后
class Rational
{
public:
Rational(int numerator = 0,int denominator = 1){}
int numerator()const{};
int denominator()const{};
private:
};
const Rational operator*(const Rational &lhs,const Rational &rhs)
{
return Rational(lhs.numerator() * rhs.numerator()
,lhs.denominator() * rhs.denominator());
}
int main()
{
Rational oneHalf(1,2);
Rational result = oneHalf * 2;
result = 2 * oneHalf;
///都通过编译了
///但是operator*是否应该成为Rational class的一个friend函数呢
///operator*可以完全通过Rational的public接口完成上面任务
///无论何时如果可以避免friend函数就应当避免,来保证class的封装性
}