Below is the code
The Code:
#include
using namespace std;
class Rational {
int num; // numerator
int den; // den
Rational::operator+
is a member function, so it has access to all members of every Rational
object.
Coding tip: this kind of things is usually written in two parts: an operator+=
that's a member, and an operator+
that's not. Like this:
Rational& Rational::operator+=(const Rational& rhs) {
num = num * rhs.den + den * rhs.num;
den *= rhs.den;
return *this;
}
Rational operator+(const Rational& lhs, const Rational& rhs) {
Rational result(lhs);
result += rhs;
return result;
}