CISC 3142 — Lab #3.4 — Rational

CISC 3142
Programming Paradigms in C++
Lab #3.4
A Minimal Rational Class

The rational.h Interface/Header File

// rational.h

#ifndef RATIONAL_H
#define RATIONAL_H

#include <iostream>

class Rational {
public:
	Rational(int num, int denom=1);
	Rational mul(const Rational &r) const;
	Rational &mulInPlace(const Rational &r);

	void print(std::ostream &os) const;
private:
	int num, denom;
};

inline std::ostream &operator <<(std::ostream &os, const Rational &r) {r.print(os); return os;}

#endif

The Include Guard/

#ifndef RATIONAL_H
#define RATIONAL_H

…

inline std::ostream &operator <<(std::ostream &os, const Rational &r) {r.print(os); return os;}

#endif

The Constructor

	…
	Rational(int num, int denom=1);
	…
};

The Mulitplication Functions

	…
	Rational mul(const Rational &r) const;
	Rational &mulInPlace(const Rational &r);
	…

The print Function and << Operator

…
class Rational {
	…
	void print(std::ostream &os) const;
	…
};

inline std::ostream &operator <<(std::ostream &os, const Rational &r) {r.print(os); return os;}

You may be able to figure out the details; we will cover them when we get to operator overloading.

The rational_app.cpp Application

Given the interface (.h file, we can begin writing our application (this can happen simultaneously with the coding of the implementation (rational.cpp) file
#include 

#include "rational.h"

using namespace std;

int main() {
	Rational r1(1, 2), r2 {3};

	cout << "r1: ";
	r1.print(cout);
	cout << endl;
	
	cout << "r2: " << r2 << endl;

	Rational r3 = r1.mul(r2);
	cout << "r3: " << r3 << endl;

	r1.mulInPlace(r2);

	cout << "r1: " << r1 << endl;

	
	return 0;
}

The rational.cpp Implementation File

#include <iostream>

#include "rational.h"
#include "rational_exception.h"

using namespace std;

Rational::Rational(int num, int denom) : num(num), denom(denom) {
	if (denom == 0) throw RationalException("0 denominator");
}

Rational Rational::mul(const Rational &r) const {
	Rational result = *this;
	return result.mulInPlace(r);
}

Rational &Rational::mulInPlace(const Rational &r) {
	num = num * r.num;
	denom = denom * r.denom;
	return *this;
}

void Rational::print(ostream &os) const {
	os << num;
	if (denom != 1)
		os << "/" << denom;
	else
		os << "";
}

The Multiplication Operations

Rational Rational::mul(const Rational &r) const {
	Rational result = *this;
	return result.mulInPlace(r);
}

Rational &Rational::mulInPlace(const Rational &r) {
	num = num * r.num;
	denom = denom * r.denom;
	return *this;
}

Code Used in this Lecture