我正在实现一个表示分数的C++类。下面是我的代码。
我现在有两个小问题。现在正在尝试呼叫。
仅仅导致这个错误:
我只想要这个:
class Fraction
{
public:
Fraction(char i);
Fraction(int i);
Fraction(short i);
Fraction(long int l);
#ifdef __LP64__
Fraction(long long l);
#endif
Fraction(float f);
Fraction(double d);
Fraction(double x, double y);
Fraction operator +() const;
Fraction operator -() const;
Fraction& operator +=(const Fraction& other);
Fraction& operator -=(const Fraction& other);
Fraction& operator *=(const Fraction& other);
Fraction& operator /=(const Fraction& other);
bool operator ==(const Fraction& other);
bool operator !=(const Fraction& other);
bool operator >(const Fraction& other);
bool operator <(const Fraction& other);
bool operator >=(const Fraction& other);
bool operator <=(const Fraction& other);
operator double();
operator float();
static void commonize(Fraction& a, Fraction& b);
void shorten();
double getNumerator();
double getDenominator();
friend Fraction operator +(Fraction const& a, Fraction const& b);
friend Fraction operator -(Fraction const& a, Fraction const& b);
friend Fraction operator *(Fraction const& a, Fraction const& b);
friend Fraction operator /(Fraction const& a, Fraction const& b);
friend ostream& operator <<( ostream& o, const Fraction f);
protected:
double numerator, denominator;
};
我现在有两个小问题。现在正在尝试呼叫。
Fraction a(1, 2);
cout << (3 + a) << endl;
仅仅导致这个错误:
fractiontest.cpp:26: error: ambiguous overload for ‘operator+’ in ‘3 + a’
fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in>
fractiontest.cpp:26: note: operator+(int, float) <built-in>
我只想要这个:
explicit operator double();
explicit operator float();
但显然,这并不起作用。我希望只有在使用转换符号时才调用这两个转换符号。例如:Fraction f(1, 2); double d = (double)(f);
int::int(Fraction f)
,因为int是一个原始类型... - Atmocreationsfloat
没错。其他的并不是非常必要,它们只是为了完整性而存在 ;) 感谢你指出来。 - Atmocreationsdouble
的构造函数,如果必要,让调用者进行转换即可。这与完整性无关,因为您未能允许从可以转换为double
或float
的 UDT 构造您的类,例如。这很好:它不是您的类的责任将任何类型强制转换为 double,它的责任是像分数一样运作。此外,为什么分数组件要使用浮点数?它们不应该是整数吗?简而言之:选择一种类型(或使您的类成为模板),并放弃其他类型。 - GManNickG