X hits on this document

48 views

0 shares

0 downloads

0 comments

7 / 14

x=  22/7

x=  66/-56 x =  -33/28

Relational Operators

The relational ops are: <    >    <=    >=    ==    !=.   These can all be overloaded, using friend functions.  Relational operations return type int, with values of either 1 (true) or 0 (false).

Here is the revised Rational class with the == relational operator overloaded in a manner consistent with the way we work with fractions.

//overloading4.cpp

//uses Rational class w/ overloaded relational 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&);

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

};

int main(){

Rational x(22,7), y(-3,8), z(x);

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

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

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

  cout << "\nx and y are ";

  if (x==y) cout << "equal";

else cout << "not equal";

  cout << "\nx and z are ";

  if (x==z) cout << "equal";

else cout << "not equal";

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

overloading.doc7 of 14

Document info
Document views48
Page views48
Page last viewedSat Dec 10 11:00:58 UTC 2016
Pages14
Paragraphs547
Words2961

Comments