X hits on this document

39 views

0 shares

0 downloads

0 comments

3 / 14

  Rational y(x);

  Rational z, w;

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

  cout << "\ny=  "; y.print();

  cout << "\nz=  "; z.print();

  w = z = y;

  cout << "\nz=  "; z.print();

  cout << "\nw=  "; w.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;

}

Output:

x=  5/18

y=  5/18

z=  0/1

z=  5/18

w=  5/18

Arithmetic Operators

When we wish to add (+) or multiply (*) two objects, neither object really owns the operator+ function or the operator* function.  For instance if x and y are both declared as objects of the Rational class, the expression x*y does not mean “multiply my data members (if “I” am x) by the corresponding data members of y.”   We just want the system to multiply the corresponding data members of x and y, perhaps to print the results, perhaps to assign the new values to a third object.  If we define the overloaded operator* function this way:

overloading.doc3 of 14

Document info
Document views39
Page views39
Page last viewedSun Dec 04 00:48:06 UTC 2016
Pages14
Paragraphs547
Words2961

Comments