// File: RationalOvld.h // Simple Operator Overload Example // A rational number is also known as a fraction. // Its data members are a numerator and denominator. // It carries out ordinary arithmentic operations, implemented using // operator overloads. The assignment operators update the attributes // of the object // The arithmetic operators return a new object, and, while they can be // members, are implemented as associated operators. // You may assume: // -- if the rational number is negative, the numerator will be negative // -- all stored rationals are reduced to lowest terms // -- Dividing by zero returns zero and sets the error data member to true #ifndef RATIONALOVERLOAD_H #define RATIONALOVERLOAD_H #include using namespace std; class RationalOvld { public: // default constructor: parameters are numerator and denominator resp. RationalOvld(int n = 0, int d = 1 ); void setNumerator(int n); void setDenominator(int d); int getNumerator() const; int getDenominator() const; // boolean comparison operators bool operator>(const RationalOvld &right) const; bool operator<(const RationalOvld &right) const; bool operator>=(const RationalOvld &right) const; bool operator<=(const RationalOvld &right) const; bool operator==(const RationalOvld &right) const; bool operator!=(const RationalOvld &right) const; // assignment operators RationalOvld& operator+=(const RationalOvld &right); // RationalOvld& operator-=(const RationalOvld &right); // RationalOvld& operator*=(const RationalOvld &right); // RationalOvld& operator/=(const RationalOvld &right); // division by zero terminates void reduce(); // reduce fraction to lowest terms private: int numerator; // numerator of fraction int denominator; // denominator of fraction }; // The arithmetic operators are overloaded as associates. // They could syntactically be members, but since they really aren't // mutators, facilitators, or inspectors, it's better they be here. RationalOvld operator+(const RationalOvld &left,const RationalOvld &right); RationalOvld operator-(const RationalOvld &left,const RationalOvld &right); RationalOvld operator*(const RationalOvld &left,const RationalOvld &right); RationalOvld operator/(const RationalOvld &left,const RationalOvld &right); // division by zero terminates // Stream insertion associated operator // Prints in lowest terms ostream& operator<<(ostream &output, const RationalOvld &right); #endif