Using an overloading operator my instructor wants us to do the following.
B = A + C; Where B, A and C are all objects.
I believe she wants us to accomplish this task by implementing the following prototype:
Rational operator+(const Rational &);
There is only one input accepted and that is an object. Does that mean I’ll need to use the this keyword when referring to A? That is where I’m running into trouble, I don’t know how to reference my call variable (I think that’s what it is) in the + operator. I figure for B I can create a temporary object inside of my + operator that stores the three parts of my class. Then return that temporary object.
clarification: When I say call variable I mean A, because a is calling the plus operator with C as the input. (I believe it is, A.operator+(C), something like that)
If you could answer in as simple as terms as possible I would appreciate it.
Thank you!
Normal approach to operator+ is to provide a non-member overload defined in the same namespace as its argument (your class Rational), with the signature such as Rational operator+(const Rational& left, const Rational& right)
And yes, if you're writing it as a member, you would be using the member variables of this as input, as you're already doing with Temp.numerator = numerator + inputObj.numerator;
(here numerator is really this->numerator, a member variable of your left-hand argument A)
PS For a simple optimization, you could also pass left argument by value: Rational operator+(Rational left, const Rational& right), but that would be jumping too far ahead.
If you have operator+= defined already (and operator+= doesn't call your class's operator+), you could write operator+ as simply
1 2 3 4 5 6
Rational Rational::operator+(const Rational& rhs) const
{
Rational ret(*this); // Make a copy of this object
ret += rhs;
return ret;
}
Otherwise, I'm not quite sure what your question is.
Your code looks fine (syntactically speaking), although I would recheck your math (adding two fractions is not simply a matter of adding the numerators and the denominators).