X hits on this document

# n_oop2.doc - page 7 / 14

48 views

0 shares

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.

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