#include using namespace std; class Fraction { /************************************ * This class enables a user to do fraction * math. To do so it overloads several operators. * It also introduces some error trapping *******************************************/ //public members public: //default constructor Fraction(){} //overloaded constructor Fraction(int numerator, int denominator) { SetNumerator(numerator); SetDenominator(denominator); } //start overloaded operators Fraction operator+ (const Fraction &F2) { //this overloads the + operator for two //fraction objects. It returns the result //as a fraction object. It gets the greatest //common denominator--better would be a routine //that returns the lowest common denominator //the "this->" pointer points to elements of //the current class Fraction temp; //declare an object of the type Fraction temp.den=this->den * F2.den; temp.num=F2.den* this->num + this->den * F2.num; return temp; } Fraction operator-(const Fraction &F2) { //does the same thing as + but with a - Fraction temp; //declare an object of the type Fraction temp.den=this->den * F2.den; temp.num=F2.den* this->num - this->den * F2.num; return temp; } Fraction operator* (const Fraction &F2) { Fraction temp; temp.den=this->den * F2.den; temp.num=this->num * F2.num; return temp; } Fraction operator/ (const Fraction &F2) { Fraction temp; temp.den=this->den * F2.num; temp.num=this->num * F2.den; return temp; } //these next operators are different because they change //the current instance of Fraction, so they //return not a third object but a pointer to the //current instance using *this Fraction& operator= (const Fraction &F2) { this->den=F2.den; this->num=F2.num; return *this; } Fraction& operator+=(const Fraction &F2) { //again we have to get the greatest common denominator this->num=F2.den * this->num + this->den * F2.num; this->den=this->den + F2.den; return *this; } Fraction& operator-=(const Fraction F2) { this->num=F2.den * this->num - this->den * F2.num; this->den=this->den * F2.den; return *this; } Fraction& operator*=(const Fraction F2) { this->num = this->num * F2.num; this->den=this->den * F2.den; return *this; } Fraction& operator/=(const Fraction F2) { this->num = this->num * F2.den; this->den=this->den * F2.num; return *this; } //print out the fraction void PrintFraction() { cout << num << "/" << den << endl; } //private members private: int num; int den; //set functions with some error trapping //these are private because I don't want //the user directly access them void SetNumerator(int n) { num = n; } void SetDenominator(int d) { if (d==0) throw "Division by 0 error"; den=d; } };