X hits on this document

38 views

0 shares

0 downloads

0 comments

8 / 14

reduce();

}

Rational::Rational (const Rational& r) : num(r.num), den(r.den){

}

void Rational::print(){

cout << num << '/' << den;

}

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

num = r.num;

  den = r.den;

  return *this;

}

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

num = num * r.num;

  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;

}

//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

y=  3/-8

z=  22/7

x and y are not equal

x and z are equal

Stream Operators:  <<   and   >>

We could overload the stream insertion and extraction ops to customize input or output of data.  So instead of the z.print function called in a previous example, we could overload the << op and use cout << z;  This also requires us to use friend functions.

overloading.doc8 of 14

Document info
Document views38
Page views38
Page last viewedSat Dec 03 18:32:14 UTC 2016
Pages14
Paragraphs547
Words2961

Comments