I created a Fraction class that is has member functions to add, subtract, multiply, and divide between two Fraction Objects along with the required default and copy constructors.
For this problem, I must used pointers (cannot use vectors!) because the Fraction objects can only be created if the user chooses to. In short, the pointer declaration and new initialization are in difference scopes.
I am trying to also overload the operator=, operator+, operator-, operator*, and operator/ to accept something like the following.
Fraction* fr1 = new Fraction(1,2);
Fraction* fr2 = new Fraction(3,4);
Fraction* fr3 = new Fraction();
fr3 = fr1 + fr2;
My current overloaded operator= member function looks like so:
Fraction* Fraction::operator=(const Fraction*& fr) {
num = fr->num;
denom = fr->denom;
return this;
}
Fraction* Fraction::operator+(const Fraction*& fr) const {
int gcd = gcdRecurEuclid(num * fr->denom + denom * fr->num, denom * fr->denom);
Fraction* temp;
temp = new Fraction((num * fr->denom + fr->num * denom) / gcd,
(denom * fr->denom) / gcd);
return temp;
}
I keep getting the error '+' : cannot add two pointers, which most likely means my overloaded operator+ is not written correctly (and/or my overloaded assignment operator). What do I need to do to correct this? Again, my instructor wants me to work with pointers, and does not want me to pass nor return copies of anything. I either need to pass by reference (or pointer? similar thing?).
As you've discovered, trying to use arithmetic operators on pointers will result in the compiler trying to do pointer arithmetic. To call your own overloaded operator on a pointer, you can either do
Fraction *f, *g; // allocated with new
f->operator+(*g); /// Urgh!
or, almost as ugly
Fraction *f, *g;
(*f) + (*g);
One easy way to make this a bit nicer is to declare three new reference variables like this:
Fraction& f1 = *pfr1;
Fraction& f2 = *pfr2;
Fraction& f3 = *ptr3;
Where the pfrN
s are the pointers to your fractions. Now if you use the reference variables, your overloaded operators will be called correctly, and you don't need to put in all the extra asterisks. The references will disappear at the end of the scope, and probably won't use any extra memory in your programme. You still need to delete
the original pointers though!