【发布时间】:2011-06-01 21:28:06
【问题描述】:
我正在实现一个代表分数的 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);
【问题讨论】:
-
如 Meyers 在“更有效的 C++”中所述,您应该三思而后行重载强制转换运算符(以及具有非显式单参数构造函数)。
-
谢谢奥利。我知道有非显式单参数(又名转换)构造函数的问题。我想我应该再考虑一下转换运算符。而且我猜你不能重载
int::int(Fraction f),因为 int 是一个原始类型...... -
你真的需要
char、short和float的构造函数吗? -
@Roland:嗯,很好……
float是的。其他的并不是真正必要的,它们只是为了完整性;)感谢您指出。 -
所有这些构造函数都是糟糕的设计。只要有一个需要一个或两个
double's,并让调用者在必要时进行转换。它与完整性无关,因为您未能允许从可以转换为double或float的 UDT 构建您的类。这很好:将任何类型转换为双精度不是您班级的责任,而是像分数一样行事。另外,为什么分数组件有浮点数?它们不应该是整数吗? tl;dr:选择一种类型(或模板化你的类)并抛弃其他类型。
标签: c++ casting type-conversion implicit-conversion