X hits on this document

51 views

0 shares

0 downloads

0 comments

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.

overloading.doc14 of 14

Document info
Document views51
Page views51
Page last viewedTue Jan 17 12:11:38 UTC 2017
Pages14
Paragraphs547
Words2961

Comments