1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
using namespace std;
class Fraction
{
private:
int num,den;
public:
//Constructors:
Fraction(){num=0;den=0;normalize();}
Fraction(const int &n, const int &d){set(n,d);}
Fraction(const int &n){set(n,1);}
//Copy-Constructor:
Fraction(Fraction const &src){num=src.num;den=src.den;}
void set(const int &n, const int &d){num=n;den=d;normalize();} //Inline, because it's declared inside the class declaration
int get_n() const {return num;}//const here makes sure that no changes are made to data members
int get_d() const {return den;}//or functions that do so are called.
//Operations:
Fraction add(const Fraction &other); //Pass by reference is faster, as no copies are made
Fraction sub(Fraction other);
Fraction mult(const Fraction &other);
Fraction div(const Fraction &other);
//Operator Overloading:
Fraction operator+(const Fraction &other){return add(other);}
Fraction operator-(const Fraction &other){return sub(other);}
Fraction operator*(const Fraction &other){return mult(other);}
Fraction operator/(const Fraction &other){return div(other);}
bool operator==(const Fraction &other){return (num==other.num && den==other.den);} //this expression evaluates to 1 if both are true or 0 if one or both are not.
bool operator>(const Fraction &other){return (num*other.den>den*other.num);}
bool operator<(const Fraction &other){return !(*this>other);}
//Supporting other operand types with friend functions
//Friend Functions are not member functions but can
//access data members:
friend Fraction operator+(const int &n, const Fraction &f1);
friend Fraction operator-(const int &n, const Fraction &f1);
friend Fraction operator*(const int &n, const Fraction &f1);
friend Fraction operator/(const int &n, const Fraction &f1);
friend ostream &operator<<(ostream &os, const Fraction &f1);
friend bool operator==(const int &n, const Fraction &f1);
friend bool operator>(const int &n, const Fraction &f1);
friend bool operator<(const int &n, const Fraction &f1);
private:
void normalize();
int gcf(const int &a, const int &b);
int lcm(const int &a, const int &b);
};
...
//Function definitions...
...
|