X hits on this document

# n_oop2.doc - page 12 / 14

61 views

0 shares

12 / 14

Rational& Rational::operator*= (const Rational& r){

num = num * r.num;

den = den * r.den;

return *this;

}

Rational Rational::operator++(){

num +=den;

return *this;

}

Rational Rational::operator++(int){

Rational temp = *this;

num +=den;

return temp;

}

int operator== (const Rational& a, const Rational& b){

return (a.num * b.den == b.num * a.den);

}

Rational operator* (const Rational& a, const Rational& b){

Rational r(a.num*b.num, a.den * b.den);

return r;

}

ostream& operator<< (ostream& out, const Rational& r){

return out << r.num << '/' << r.den;

}

//private functions used to reduce fraction

int Rational::gcd (int j, int k) {

if (k==0) return j; return gcd(k, j%k);

}

void Rational::reduce () {

int g = gcd(num, den); num /= g; den /= g;

}

Output:

x =  23/7  y = 0/1

x =  30/7  y = 23/7

x =  30/7  z = 0/1

x =  30/7  z = 30/7

Conversion Operators

We want type conversion to and from classes to look like any other ordinary type conversion.  The syntax for overloading the conversion operator is slightly different from what we have had before.