// Program: rational.cpp
// Define a type rational and operations on it
// the new type rational
struct rational {
int n;
int d; // INV: d != 0
};
// POST: b has been added to a; return value is the
// new value of a
rational& operator+= (rational& a, const rational b) {
a.n = a.n * b.d + a.d * b.n;
a.d *= b.d;
return a;
}
// POST: return value is the sum of a and b
rational operator+ (const rational a, const rational b)
{
// reduce to operator +=
rational result = a;
return result += b;
}
// POST: a has been written to o
std::ostream& operator<< (std::ostream& o, const rational a)
{
return o << a.n << "/" << a.d;
}
// POST: a has been read from i
// PRE: i starts with a rational number of the form "n/d"
std::istream& operator>> (std::istream& i, rational& a)
{
char c; // separating character, e.g. '/'
return i >> a.n >> c >> a.d;
}