X hits on this document

37 views

0 shares

0 downloads

0 comments

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.  

overloading.doc12 of 14

Document info
Document views37
Page views37
Page last viewedFri Dec 02 18:58:41 UTC 2016
Pages14
Paragraphs547
Words2961

Comments