// // Class name: rationals_v2 // Author: B. Massingill // // requires #include // -------- definition of class for rational numbers -------- // // an object of this class represents a rational number, i.e., a // fraction // class RationalNum { private: // ---- member variables ---- int numerator; int denominator; public: // ---- constructors ---- RationalNum(const int n=0, const int d=1); // ---- member functions ---- // "reduce" to simplest terms // precondition: none // postcondition: denominator is non-negative, numerator and // denominator have no common factors void reduce(); // arithmetic functions // precondition: none // postcondition: object's value has been modified by // adding/subtracting/multiplying/dividing by q; // return value is object's value (to be consistent with // other definitions of these operators) RationalNum& operator+=(const RationalNum q); RationalNum& operator-=(const RationalNum q); RationalNum& operator*=(const RationalNum q); RationalNum& operator/=(const RationalNum q); // ---- friend functions ---- // read from input stream // precondition: iStr is an input stream (already successfully // opened if an ifstream) // postcondition: // if iStr contains a fraction in the form integer/integer, // that fraction is read in and return value is true // otherwise the return value is false friend istream& operator>>(istream& iStr, RationalNum &rr); // print to output stream // precondition: oStr is an output stream (already successfully // opened if an ofstream) // postcondition: fraction has been printed on oStr, in the form // numerator/denominator friend ostream& operator<<(ostream& oStr, const RationalNum r); // comparison functions // precondition: none // postcondition: return value indicates whether p == q // (for equals), p < q (for lessThan), or p > q (for // greaterThan) friend bool operator==(const RationalNum p, const RationalNum q); friend bool operator<(const RationalNum p, const RationalNum q); friend bool operator>(const RationalNum p, const RationalNum q); friend bool operator>=(const RationalNum p, const RationalNum q); friend bool operator<=(const RationalNum p, const RationalNum q); friend bool operator!=(const RationalNum p, const RationalNum q); // arithmetic functions // precondition: none // postcondition: return value is p+q, p-q, p*q, p/q, -p as // indicated by function name friend RationalNum operator+(const RationalNum p, const RationalNum q); friend RationalNum operator-(const RationalNum p, const RationalNum q); friend RationalNum operator*(const RationalNum p, const RationalNum q); friend RationalNum operator/(const RationalNum p, const RationalNum q); friend RationalNum operator-(const RationalNum p); } ;