Effective C++ Ed. 3rd: Item 24. Declare non-member functions when type conversions should apply to all parameters

Way 1:
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

        const Rational operator*(const Rational& rhs) const;
    private:
    ...
};

Rational oneEighth(1, 8);
Rational oneHalf(1, 2);
result = oneHalf * 2;                             // fine - oneHalf.operator*(2);
result = 2 * oneHalf;                             // error! - 2.operator*(oneHalf);
Way2:
class Rational {
  ...                                             // contains no operator*
};

const Rational operator*(const Rational& lhs,     // now a non-member
                         const Rational& rhs)     // function
{
  return Rational(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());
}

Rational oneFourth(1, 4);
Rational result;
result = oneFourth * 2;                           // fine
result = 2 * oneFourth;                           // hooray, it works!
Result: As multiplication should be commutative, Way2 should be used when type conversions should apply to all parameters.

prev | next
Cheers and try hosting at Linode.

No comments:

Post a Comment