#include using namespace std; class rational{ public: int n, d; rational():n(0),d(1){} rational(int a, int b=1):n(a),d(b){} // copy constructor rational(rational &r):n(r.n),d(r.d){} const rational operator+(const rational &rhs){ int num = n*rhs.d + rhs.n*d; int den = d*rhs.d; return rational(num,den); } const rational operator-(const rational &rhs){ int num = n*rhs.d - rhs.n*d; int den = d*rhs.d; return rational(num,den); } // show anonymous variable can call method rational setnd(int a, int b){ return rational(a,b); } // assignment operator rational operator=(const rational &rhs){ if(&rhs != this){ // do nothing if a = a n = rhs.n; d = rhs.d; } return *this; } friend ostream& operator<<(ostream &o, rational &r); }; ostream& operator<<(ostream &o, rational &r){ o << r.n <<"/" << r.d << " "; return o; } void main(){ rational p(1,2), q(1,3), z(p); cout << p << " " << q << " " << z << endl; // prevent the following by making rational + return const // z = (p + q).setnd(3,4); z = p + q; cout << z << endl; z = p - q; cout << z << endl; z = z + 1;// 1 is auto promoted to rational(1,1) cout << z << endl; }