I'm currently trying to create a member function that adds an object, Fraction f, to the current object and returns a reference to the current object. my second function is a non-friend helper operator that adds two Fraction objects and returns a copy of the result. I'm not exactly sure how to go about doing this and was looking for some advice. Pretty much the object(s) are just fractions that have been simplified earlier within a previous member function. Essentially all I'm doing is adding simplified fractions. Here's what I have so far:
//header.h
class Fraction {
int num;
int den;
public:
Fraction();
Fraction(int, int);
Fraction& operator+=(const Fraction& f);
friend bool operator==(const Fraction&, const Fraction&);
void simplify();
void display() const;
};
Fraction operator+(const Fraction&, const Fraction&);
and the module:
//module.cpp
#include "Fraction.h"
#include <iostream>
Fraction::Fraction() {
num = 0;
den = 0;
}
Fraction::Fraction(int n, int d) {
num = n;
den = d;
simplify();
}
void Fraction::simplify() {
int temp = den;
int a = num;
int b = den;
int gcd;
if (b > a) {
b = num;
a = den;
}
while (temp != 0) {
temp = a % b;
a = b;
b = temp;
}
gcd = a;
num /= gcd;
den /= gcd;
}
void Fraction::display() const {
std::cout << num << "/" << den << std::endl;
}
//member function in question
Fraction& Fraction::operator+=(const Fraction& f) {
num += f.num;
den += f.den;
return *this;
}
//member function in question
Fraction operator+(const Fraction&, const Fraction&) {
}
EDIT: guess I wasn't as clear previously and that's partly due to the helper function not being revealed. I tried defining the member function and the above code is currently what I have at the moment. I'm not sure if it's logically sound or not as I am still going through the other definitions. the non friend helper operator is the one I am stumped on and do not know what to do. If I can get some help on whether the definition I have for the += member operator is correct and some advice on how to approach the non friend helper operator, that would be great. sorry for any confusion.
since you have the fractions simplified, all you have to do is to use this equation:
and the code will be as follows:
Fraction& Fraction::operator+=(const Fraction& f) {
num = num * f.den + f.num * den;
den *= f.den;
simplify();
return * this;
}
EDIT: take a look at this question for more about operator overloading