X hits on this document

46 views

0 shares

0 downloads

0 comments

10 / 14

  den = den * r.den;

  return *this;

}

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 =  22/7 and y =  0/1

The input >> operator can be overloaded in a similar way, e.g.:

friend istream& operator >> (istream& in, Rational r){

cout << "numerator = "; in >> r.num;

cout << "denominator = "; in >> r.den;

r.reduce();

return in;

}

Increment and Decrement Operators

These are unary operators, and we must distinguish between prefix (++x) and postfix (x++).

What does it mean to increment a fraction?  For ex.,

2323 + 7num + den

---+1=--------=------------

777

overloading.doc10 of 14

Document info
Document views46
Page views46
Page last viewedThu Dec 08 14:39:52 UTC 2016
Pages14
Paragraphs547
Words2961

Comments