X hits on this document

# n_oop2.doc - page 14 / 14

51 views

0 shares

14 / 14

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 =  -5/8 = -0.625

PI =  22/7 = 3.14286

Subscript Operator []

The overloaded subscript operator can be used as an access function , providing public access to private data:

e.g,

int& Rational::operator[] (int i){

if (i==1) return num;

if (i==2) return den;

}

then, in main()

cout << x[1];   would display the num of x.

 Document views 51 Page views 51 Page last viewed Tue Jan 17 12:11:38 UTC 2017 Pages 14 Paragraphs 547 Words 2961