X hits on this document

# n_oop2.doc - page 2 / 14

28 views

0 shares

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 {

public:

Rational (int=0, int=1);

Rational (const Rational&);

void print();

Rational& operator= (const Rational&);

private:

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);