X hits on this document

# n_oop2.doc - page 8 / 14

53 views

0 shares

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.

 Document views 53 Page views 53 Page last viewed Wed Jan 18 16:10:02 UTC 2017 Pages 14 Paragraphs 547 Words 2961