X hits on this document

43 views

0 shares

0 downloads

0 comments

9 / 14

The ostream class is defined in the iostream.h header file.  If x is a Rational object, cout<< x would invoke a call to the overloaded << operator with two objects as arguments:  cout and x.  The return is cout so the statement can be chained, e.g.,

cout << "x= " << x;

Program:

//overloading5.cpp

//uses Rational class w/ overloaded output operator added

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

  friend int operator== (const Rational&, const Rational&);

  friend ostream& operator<< (ostream&, const Rational&);

public:

  Rational (int=0, int=1);

  Rational (const Rational&);

//   void print();  no longer needed

  Rational& operator= (const Rational&);

  Rational& operator*= (const Rational&);

private:

int num, den;

  int gcd (int, int);

  void reduce ();

};

int main(){

Rational x(22,7), y;

  cout << "x =  " << x << " and y =  " << y << endl;

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

}

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

num = r.num;

  den = r.den;

  return *this;

}

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

num = num * r.num;

overloading.doc9 of 14

Document info
Document views43
Page views43
Page last viewedMon Dec 05 12:05:51 UTC 2016
Pages14
Paragraphs547
Words2961

Comments