我最近正在学习C ++并且有一些基本的Fraction类来实现运算符重载。其中一个要重载的运算符是*
。
将两种分数类型相乘的快速实现:
Fraction Fraction::operator* (const Fraction &rightOperand)
{
return Fraction(numerator * rightOperand.numerator, denominator * rightOperand.denominator);
}
一个用于乘以右手操作数为int
的位置:
Fraction Fraction::operator* (int rightOperand)
{
return Fraction(numerator * rightOperand, denominator);
}
然后,因为乘法是可交换的,所以乘以 left hand运算符应该只是:
// declared as friend
Fraction operator* (int leftOperand, const Fraction &rightOperand)
{
return rightOperand * leftOperand; // should use the overload above, right?
}
但是,在最后一个函数中,'*'给出错误:
没有运算符“*”匹配这些操作数 - 操作数类型是:const Fraction * int
我将参数设置为const引用,因为它们没有写入...在这种情况下这是不正确的还是有某种方法?当然,我不必将成员函数的全部重复定义为具有两个参数的全局自由函数,只是为了将const
添加到参数中?