class Rational { public: Rational(int numerator = 0, // ctor is deliberately not explicit; int denominator = 1); // allows implicit int-to-Rational // conversions int numerator() const; // accessors for numerator and int denominator() const; // denominator - see Item 22 private: …… }; |
class Rational { public: …… const Rational operator*(const Rational& rhs) const; }; |
Rational oneEighth(1, 8); Rational oneHalf(1, 2); Rational result = oneHalf * oneEighth; // fine result = result * oneEighth; // fine |
但是你并不感到满意。你还希望支持混合模式的操作,以便让 Rationals 能够和其它类型(例如,int)相乘。毕竟,很少有事情像两个数相乘那么正常,即使它们碰巧是数字的不同类型。