我正在学习 C++ 中的重载运算符,但我遇到了问题。
我写了一个(原始)类来表示 C++ 中的一个分数,以及一个将其中两个相乘的函数。
如果我想使用函数将分数乘以整数,那么一切都很好(感谢转换构造函数:P)。但现在我想用重载的 * 乘以分数,就像两个数字一样。乘法first_fraction * second_fraction
效果很好,但编译器不想将数字转换为fraction * 2
. (它给出了这个错误:错误 C2666:'operator *':2 个重载有类似的转换)
如果我手动转换它,fraction*static_cast<CFraction>(2)
则可以再次使用它。
谁能解释我做错了什么?这是完整的代码:
#include <iostream>
using namespace std;
class CFraction
{
private:
int m_numerator;
int m_denominator;
public:
// Normal constructor, default constructor and conversion constructor
CFraction(int numerator=0,int denominator = 1) : m_numerator(numerator), m_denominator(denominator)
{
}
int numerator() const { return m_numerator; }
void numerator(int numerator) { m_numerator = numerator; }
int denominator() const { return m_denominator; }
void denominator(int denominator) { m_denominator = denominator; }
// Conversion to decimal form
operator float()
{
return m_numerator / static_cast<float>(m_denominator);
}
};
// Function to multiply 2 fractions
CFraction multiplication(const CFraction& f1,const CFraction& f2)
{
return CFraction(f1.numerator()*f2.numerator(),f1.denominator()*f2.denominator());
}
// Overloaded opearator to multiply 2 fractions
CFraction operator *(const CFraction& f1,const CFraction& f2)
{
return CFraction(f1.numerator()*f2.numerator(),f1.denominator()*f2.denominator());
}
int main()
{
CFraction fraction1(3,4);
cout << "Fraction: "<< fraction1.numerator() << "/" << fraction1.denominator() << endl;
cout << "Decimal: " << static_cast<float>(fraction1) << endl;
// Multiplication by function works very well
CFraction result = multiplication(fraction1,2);
// (ERROR) Compiller won't convert 2 to CFraction class
CFraction result1 = fraction1*2;
// Using manually covnerted integer - works again
CFraction result2 = fraction1*static_cast<CFraction>(2);
cout << "Multiplied by 2: " << static_cast<float>(result);
getchar();
return 0;
}
PS。如果重要的话,我正在使用 MS Visual C++ 2010