X hits on this document

42 views

0 shares

0 downloads

0 comments

6 / 14

int main(){

Rational x(22,7), y(-3, 8), z(x);

  cout << "\nx=  "; x.print();

  x = x * y;

  cout << "\nx=  "; x.print();

  x = z;

  cout << "\nx=  "; x.print();

  x *= y;

  cout << "\nx=  "; x.print();

  x.reduce(); cout << " x =  "; x.print();

  cout << "\n\n\nPress any key to close console window:  ";

  char c; cin >> c;

return 0;

}

Rational::Rational (int n, int d) : num (n), den (d){

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;

reduce();

  return *this;

}

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

x=  -33/28

overloading.doc6 of 14

Document info
Document views42
Page views42
Page last viewedMon Dec 05 10:09:41 UTC 2016
Pages14
Paragraphs547
Words2961

Comments