问题描述
我有一个分数类。
我需要对分数对象进行3次运算,即
I need to do 3 operations on Fraction Object i.e
- 将两个小数对象相乘。例如F1 * F2
- 将Fraction对象乘以整数。对于前。 F1 * 3
- 将整数与小数对象相乘。对于前。 3 * F1。
前两种情况可以通过重写分数类*运算符来实现。
The first two case can be achieved by overriding the Fraction Class * operator.
Fraction operator*(const Fraction&);
Fraction operator*(const int&);
但是如何将整数与分数对象相乘?第三种情况
but how to multiply an integer by a fraction Object? The third case
任何建议?
PS:我不想处理整数作为分数对象,例如(3/1),然后进行乘法。
推荐答案
您需要实现运算符重载作为自由函数,例如:
You need to implement the operator overload as a free function, like this:
Fraction operator *(int lhs, Fraction rhs)
{
rhs *= lhs;
return rhs;
}
请注意,我已经根据实现了该功能分数:: operator * =(int)
(请参见为何认为这是一种好习惯) 。如果不存在此功能,则可能需要将第二个参数传递为 const Fraction& rhs
并提供不同的实现。
Note that I have implemented the function in terms of Fraction::operator*=(int)
(see here why this is considered good practice). If this function is not present, you might want to pass the second parameter as const Fraction& rhs
and provide a different implementation.
此外,请注意,处理这种情况的惯用方法是允许隐式构造 Fraction
实例由一个 int
参数组成,因此您的约束对我来说似乎有点尴尬。还要注意,您的 Fraction
类的用户可能希望所有算术运算都是可能的(为什么要有 operator *
,但不是 operator /
??)。为了减少在这种情况下要编写的手动代码量,请可能会很有帮助。
Besides, note that an idiomatic way to handle this scenario is to allow an implicit construction of Fraction
instances by a single int
argument, so your constraint seems a bit awkward to me. Further note that users of your Fraction
class might expect all arithmetic operations to be possible (why should there be operator*
, but not operator/
?). To reduce the amount of manual code to be written in such cases, the boost operator library can be of great help.
这篇关于如何在C ++中用分数对象乘以整数常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!