This sites tutorial section seems to be missing the subject of operator overloading.
Perhaps an example would help.
The 2 Rational objects you are trying to add (a and b) are the operands in a+b. The right operand (b) is the one supplied as a parameter to the function.
The left operand (a) is the one
calling the function. Do you know about the
this pointer?
The function should return a Rational object, so you need to construct one in the function.
What constructors are available in the Rational class?
If you only have a default constructor (taking no arguments) then you can make it work like so:
1 2 3 4 5 6 7
|
Rational Rational::operator+(const Rational & b)const
{
Rational retVal;// must assign the members here in the function
retVal.num = this->num * b.den + this->den * b.num;// use of "this" is optional
retVal.den = this->den * b.den;
return retVal;
}
|
If there is a constructor which takes 2 integers and assigns them to num and den, then the function can be written very simply as:
1 2 3 4 5
|
Rational Rational::operator+(const Rational & b)const
{
// constructing the returned object in the return statement.
return Rational( num * b.den + den * b.num, den * b.den );// omitting use of "this" (it is implied)
}
|
Hopefully this example will help with other operators you need to write.