Rational 1: Using Member Functions

Our first implementation of the rational class illustrates the basic structure of a class definition. This implementation has a constructor, an input operator, an oputput operator, and a collection of simple arithmetic operators.

Note the syntax used to access member functions in the main function. Of particular interest is the line (r1.add(r2)).write( cout );. The first part of this line ((r1.add(r2))) constructs an unnamed value of type rational. We then invoke the write member function of this unnamed value.

Our next implementation adds functions that overload several of the standard operator symbols (+, <<, and >>) in an effort to improve the readability of the code.


//
// Defining the class rational 
//   -- first attempt, using standard function notation
// 
// by A.B. Maccabe  2/27/97
//

#include <iostream.h>


class Rational {
public:
    // Constructors
    Rational( int n = 0, int d = 1 ) {
	num = n;
	denom = d;
    };

    // I/O
    void read( istream &in ) {
	char slash;
	in >> num >> slash >> denom;
    };

    void write( ostream &out ) {
	out << num << '/' << denom;
    };

    // arithmetic
    Rational neg( ) {
	return Rational( -num, denom );
    };

    Rational add( Rational rat ) {
	return Rational( num*rat.denom + denom*rat.num, denom*rat.denom );
    };

    Rational sub( Rational rat ) {
	return add( rat.neg() );
    };

    Rational mpy( Rational rat ) {
	return Rational( num*rat.num, denom*rat.denom );
    };

    Rational div( Rational rat ) {
	return Rational( num*rat.denom, denom*rat.num );
    };

    
private:
    int num, denom;
};



int main( ) {
    cout << "Enter a rational (e.g., 12/7):" << flush;
    Rational r1;
    r1.read( cin );

    cout << "Enter a second rational:" << flush;
    Rational r2;
    r2.read( cin );

    r1.write( cout );
    cout << " + ";
    r2.write( cout );
    cout << " = ";
    (r1.add(r2)).write( cout );
    cout << endl;
}


Barney Maccabe
Last modified: Wed Apr 2 17:43:37 MST