class Fraction
{
private: // don't really need this
unsigned den, num;
public:
Fraction(void); // initialization
void add(const Fraction b, Fraction &sum);
void sub(const Fraction b, Fraction &diff);
void mult(const Fraction b, Fraction &product);
void div(const Fraction b, Fraction "ient);
unsigned getDenominator(void);
unsigned getNumerator(void);
void setDenominator(unsigned den);
void setNumerator(unsigned num);
float getValue(void);
void simplify(void);
};
Note that the class definition should be contained in a file named
fraction.h. The implementation of the member functions should
be contained in a source file named fraction.cc as follows
(portions of it):
#include "fraction.h"
Fraction::Fraction(void)
{
den = num = 1;
}
void Fraction::mult(const Fraction b, Fraction &product)
{
product.num = num * b.num;
product.den = den * b.den;
simplify();
}
float Fraction::getValue(void)
{
return (float)num/den;
}
void Fraction::simplify(void)
{
// okay, I am lazy...
}
void Fraction::setDenominator(unsigned u)
{
den = u;
}
void Fraction::setNumerator(unsigned u)
{
num = u;
}
unsigned Fraction::getDenominator(void)
{
return den;
}
unsigned Fraction::getNumerator(void)
{
return num;
}
// ... etc
Now that we have the source file, we can compile it using the following command:
g++ -O -Wall -g -c fraction.cc
If the compilation is successful, we end up with an object file
fraction.o.
Next, we can start to write code that uses fractions. For example,
we may want to let a user input two fractions, and the program
prints the product. We'll call this source file area.cc:
#include "fraction.h"
#include <iostream>
using namespace std;
void computeFracProduct(void)
{
unsigned u1, u2;
cout << "num1: numerator denominator" << endl;
cin >> u1 >> u2;
Fraction f1;
f1.setNumerator(u1);
f1.setDenominator(u2);
cout << "num2: numerator denominator" << endl;
cin >> u1 >> u2;
Fraction f2;
f2.setNumerator(u1);
f2.setDenominator(u2);
Fraction product;
f1.mult(f2, product);
cout << "product is " << product.getNumerator() << "/" << product.getDenominator() << endl;
}
int main(void)
{
computeFracProduct();
}
We now compile the consumer source file:
g++ -g -Wall -O -c area.cc
If this is successful, then we link the two object files:
g++ -g -o area area.o fraction.o