#ifndef RATIONAL_HPP
#define RATIONAL_HPP
// A class representing rational numbers (fractions)
class Rational {
public:
// Methods defined in the class body are "inline." They are expanded at the call site and so
// don't have any function call overhead (they are faster). However, each time they are used
// their code is replicated. You should only inline methods that are very short and simple.
// There is no default constructor (constructor with no parameters). Because at least one
// other constructor exists, the compiler won't generate a default constructor. This means
// it isn't possible to declare a Rational without initializing it.
// Constructor with a default value for the second parameter as a convenience.
Rational( int n, int d = 1 )
{ set( n, d ); }
// Accessor methods.
// The use of 'const' means these methods can be applied to a constant Rational.
int get_numerator( ) const
{ return numerator; }
int get_denominator( ) const
{ return denominator; }
// Rational objects are mutable (is that good?). This method changes the value.
void set( int new_n, int new_d )
{ numerator = new_n; denominator = new_d; reduce(); }
// The usual arithmetic operations.
Rational operator+( const Rational &other ) const;
Rational operator-( const Rational &other ) const;
Rational operator*( const Rational &other ) const;
Rational operator/( const Rational &other ) const;
private:
int numerator;
int denominator;
// This private method can only be used by other methods.
void reduce( );
};
#endif