X hits on this document





2 / 14

The & is for efficiency: the function does not make a local copy of the object.  The const is for safety:  the function cannot alter the original.

If x and y are both declared as type Rational, then the expression x=y will assign the values of the data members of y to the corresponding data members of x. Then, why do we need the return type (why not void?).

If x, y, and z  are all declared as type Rational, we can chain assignment operations as:

x = y = z;

We can only do that if the first expression evaluated, y = z, returns a value that can then be used as input to the next assignment expression in sequence.

So what does the = operation return?  It must return an object, the object it belongs to.  We have not seen this yet.  We would know how to “return num;” or “return dem;” but we wish to return the entire object.  Which object?  This object whose operator= function is currently executing.  We use a special predefined pointer called this.

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

num = r.num;

den = r.den;

return *this;//return a reference to the object that owns

}// this function

Notice that this is not the same as the copy constructor.  The copy constructor is called by an initialization statement and creates an object.  An assignment calls the assignment operator and operates on objects that are already declared.

The complete program is:


//Rational class w/ overloaded = operator

//Borland C++ 5.02

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

//modified from Hubbard

#include <iostream>

class Rational {


  Rational (int=0, int=1);

  Rational (const Rational&);

void print();

  Rational& operator= (const Rational&);


int num, den;

  int gcd (int j, int k) {if (k==0) return j; return gcd(k, j%k);}

  void reduce () {int g = gcd(num, den); num /= g; den /= g;}


int main(){

Rational x(100,360);

overloading.doc2 of 14

Document info
Document views28
Page views28
Page last viewedSun Oct 23 03:40:19 UTC 2016