I'm learning C++ recently and have some basic Fraction class to implement operator overloads on. One of the operators to be overloaded is *
.
A quick implementation for multiplying two Fraction types:
Fraction Fraction::operator* (const Fraction &rightOperand)
{
return Fraction(numerator * rightOperand.numerator, denominator * rightOperand.denominator);
}
And one for multiplying where the right hand operand is an int
:
Fraction Fraction::operator* (int rightOperand)
{
return Fraction(numerator * rightOperand, denominator);
}
Then, because multiplication is commutative, multiplying where the left hand operator should be simply:
// declared as friend
Fraction operator* (int leftOperand, const Fraction &rightOperand)
{
return rightOperand * leftOperand; // should use the overload above, right?
}
However, in the last function, the '*' gives an error:
no operator "*" matches these operands -- operand types are: const Fraction * int
I set the parameters to be const references because they are not written to... is this incorrect in this case or is there some way around this? Surely I don't have to define a whole load of duplications of the member functions as global free functions with two arguments just to add const
to the parameters?