#ifndef FRACTION_HPP
#define FRACTION_HPP
// **** BEGIN namespace CPPBook ********************************
namespace CPPBook {
/* Fraction class
*/
class Fraction {
/* private: no access from outside
*/
private:
int numer;
int denom;
/* public interface
*/
public:
// default constructor
Fraction();
// constructor from int (denominator)
Fraction(int);
// constructor from two ints (numerator and denominator)
Fraction(int, int);
// output
void print();
};
} // **** END namespace CPPBook ********************************
#endif /* FRACTION_HPP */
******************************************************************************************************
******************************************************************************************************
// include header file with the class declaration
#include "frac.hpp"
// include standard header files
#include <iostream>
#include <cstdlib>
// **** BEGIN namespace CPPBook ********************************
namespace CPPBook {
/* default constructor
*/
Fraction::Fraction()
: numer(0), denom(1) // initialize fraction with 0
{
// no further statements
}
/* constructor for whole number
*/
Fraction::Fraction(int n)
: numer(n), denom(1) // initialize fraction with n
{
// no further statements
}
/* constructor for numerator and denominator
*/
Fraction::Fraction(int n, int d)
: numer(n), denom(d) // initialize numerator and denominator as passed
{
// 0 as denominator is not allowed
if (d == 0) {
// exit program with error message
std::cerr << "error: denominator is 0" << std::endl;
std::exit(EXIT_FAILURE);
}
}
/* print
*/
void Fraction::print()
{
std::cout << numer << '/' << denom << std::endl;
}
} // **** END namespace CPPBook ********************************
Here's an example that does fractions. Start by compling this example and then modifying it to suite your needs.
http://www.josuttis.com/cppbook/classes/frac1.cpp.html