#include "Rational.h" #include #include using std::ostream; using std::domain_error; void Rational:: reduce() { /* needs to be implemented: reduce to simplest form & put - in numerator if any */ } Rational:: Rational(int n, int d) throw(domain_error): nume(n), denom(d) { if (d == 0) throw domain_error("Rational 0 denominator"); // the rest of this won't execute because of throw (like return) reduce(); // do we want to force this or not? } Rational Rational:: operator-() const { Rational temp(-nume, denom); temp.reduce(); return temp; } // cast operator overloads Rational:: operator int() const { return nume / denom; // integer truncated division } Rational:: operator double() const { return (double) nume / denom; } double Rational:: compare(const Rational & rhs) const { double dleft = (double) *this; double dright = (double) rhs; return dleft - dright; } Rational Rational:: operator+(const Rational & rhs) const { int num = this->nume * rhs.denom + rhs.nume * this->denom; Rational temp(num, this->denom * rhs.denom); // will reduce return temp; } bool Rational:: operator==(const Rational & rhs) const { /* if constructor doesn't reduce, must create temp variables, copies of this and rhs, reduce, then check Rational templ(*this); Rational tempr(rhs); templ.reduce(); tempr.reduce(); return templ.nume == tempr.nume && templ.denom==tempr.denom; */ // assuming constructor reduces return nume == rhs.nume && denom == rhs.denom; } // mutating operators Rational & Rational:: operator+=(const Rational & rhs) { *this = *this + rhs; return *this; } ostream & operator<<(ostream & os, const Rational & r) { os << r.nume << "/" << r.denom; return os; }