Operator overloading with fractions

I'm sort of lost on how to write code that allows for the multiplication, subtraction, and division of fractions within a fractions class. Could anyone give me an outline of how to do so?
Last edited on
Say you have a class fractions. Simply add in operator calls for each thing, and implement it. Here is a quick example (just multiplication, you do the rest):
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
class Fraction {
    public:
        Fraction(int num, int denum) : _num(num), _denum(denum) {}
        ~Fraction() = default;

        void operator*= (const Fraction& other) {
            this->_num *= other._num;
            this->_denum *= other._denum;
        }
        void operator*= (int other) {
            this->_num *= other;
        }

    private:
        int _num;
        int _denum;
};

Fraction operator* (const Fraction& lhs, const Fraction& rhs) {
    Fraction temp (lhs);
    temp *= rhs;
    return temp;
}
Fraction operator* (const Fraction& lhs, int rhs) {
    Fraction temp (lhs);
    temp *= rhs;
    return temp;
}
Fraction operator* (int lhs, const Fraction& rhs) {
    return rhs * lhs;
}

// example use
int main() {
    Fraction f1 (5, 8);
    Fraction f2 = f1 * -3;
    Fraction f3 = 4 * f1 * f2;
    f2 *= f1 * f3;
    f1 *= -3;
    return 0;
}
Topic archived. No new replies allowed.