X hits on this document

52 views

0 shares

0 downloads

0 comments

5 / 14

  return *this;

}

Rational operator* (const Rational& a, const Rational& b){

Rational r(a.num*b.num, a.den * b.den);

  return r;

}

Output:

z=  22/7

x=  -33/28

Notice that the scope resolution operator :: is not used in the implementation because operator* is not a member function of the Rational class; it is a friend of the class, but not part of it.

Arithmetic Assignment Operators

Overloading arithmetic assignment operators (+=, *=, -=) is almost identical to overloading the assignment operator (not to overloading the arithmetic ops).  

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

num = num * r.num;

den = den * r.den;

return *this;

}

and here's the whole revised program:

//overloading3.cpp

//uses Rational class w/ overloaded *= operator

//Borland C++ 5.02

//Project Target Type: Application - Target Model: Console

//modified from Hubbard

#include <iostream>

class Rational {

friend Rational operator* (const Rational&, const Rational&);

public:

  Rational (int=0, int=1);

  Rational (const Rational&);

void print();

  Rational& operator= (const Rational&);

  Rational& operator*= (const Rational&);

private:

int num, den;

  int gcd (int, int);

  void reduce ();

};

overloading.doc5 of 14

Document info
Document views52
Page views52
Page last viewedTue Jan 17 17:35:29 UTC 2017
Pages14
Paragraphs547
Words2961

Comments