(没有)在数值表达式中使用隐式转换?
(There's no) implicit conversion when used in numerical expression?
我有一些特殊的数字class。 class 可以由一个 double 构造:
struct FancyDouble{
FancyDouble& operator = (double v){
this->value = v;
return *this;
}
};
FancyDouble myFancyDouble = 5.0;
class 提供了从 double
到 FancyDouble
的(隐式)转换。有没有办法做相反的事情? 所以当我在数字表达式中使用 FancyDouble
时,我想写:
double a = 123;
double b = b * myFancyDouble;
我查看了参考资料,我认为这是不可能的,但我不是很确定。
是的,你可以。它们被称为转换运算符:
struct FancyDouble
{
// your things here
operator double() { return this->value; }
};
您可以转换为任何类型,而不仅仅是内置类型。它们通常也被标记为 const
(虽然我没有在这里展示核心概念)。
请注意,您的结构(如图所示)并不完全允许从 double
到 FancyDouble
的隐式转换;您的 operator=
仅意味着您可以在赋值的右侧使用双精度数,但是如果您有一个 FancyDouble
函数参数,它将不起作用,因为您需要的是接受双精度而不是赋值运算符的构造函数。
void foo(FancyDouble fd);
foo(4.4); // does not work because you can't construct a FancyDouble from a double
// even though you have an assignment operator
你会这样做:
struct FancyDouble
{
// your things here
FancyDouble(double d) { /* initialization here */ }
};
有了这个,你只需要一个接受 FancyDouble
而不是 double
的 operator=
,并且转换会自动完成:
struct FancyDouble
{
// your things here
FancyDouble(double d) { /* initialization here */ }
FancyDouble& operator=(FancyDouble fd) { /* assignment here */ }
};
FancyDouble fd = 4.2; // works
fd = 5.5; // also works, because FancyDouble can be constructed implicitly from a double
我有一些特殊的数字class。 class 可以由一个 double 构造:
struct FancyDouble{
FancyDouble& operator = (double v){
this->value = v;
return *this;
}
};
FancyDouble myFancyDouble = 5.0;
class 提供了从 double
到 FancyDouble
的(隐式)转换。有没有办法做相反的事情? 所以当我在数字表达式中使用 FancyDouble
时,我想写:
double a = 123;
double b = b * myFancyDouble;
我查看了参考资料,我认为这是不可能的,但我不是很确定。
是的,你可以。它们被称为转换运算符:
struct FancyDouble
{
// your things here
operator double() { return this->value; }
};
您可以转换为任何类型,而不仅仅是内置类型。它们通常也被标记为 const
(虽然我没有在这里展示核心概念)。
请注意,您的结构(如图所示)并不完全允许从 double
到 FancyDouble
的隐式转换;您的 operator=
仅意味着您可以在赋值的右侧使用双精度数,但是如果您有一个 FancyDouble
函数参数,它将不起作用,因为您需要的是接受双精度而不是赋值运算符的构造函数。
void foo(FancyDouble fd);
foo(4.4); // does not work because you can't construct a FancyDouble from a double
// even though you have an assignment operator
你会这样做:
struct FancyDouble
{
// your things here
FancyDouble(double d) { /* initialization here */ }
};
有了这个,你只需要一个接受 FancyDouble
而不是 double
的 operator=
,并且转换会自动完成:
struct FancyDouble
{
// your things here
FancyDouble(double d) { /* initialization here */ }
FancyDouble& operator=(FancyDouble fd) { /* assignment here */ }
};
FancyDouble fd = 4.2; // works
fd = 5.5; // also works, because FancyDouble can be constructed implicitly from a double