(没有)在数值表达式中使用隐式转换?

Mic*_*ael 2 c++ implicit-conversion

我有一些特殊的数字类.该类可以用双构造:

struct FancyDouble{
  FancyDouble& operator = (double v){
    this->value = v;
    return *this;
  }
};

FancyDouble myFancyDouble = 5.0;
Run Code Online (Sandbox Code Playgroud)

类从提供了一种(隐含的)转换doubleFancyDouble.有没有办法做相反的事情?所以当我FancyDouble在数字表达式中使用a 时,我想写:

double a = 123;
double b = b * myFancyDouble;
Run Code Online (Sandbox Code Playgroud)

我查看了参考文献,我认为这是不可能的,但我不是很确定.

zne*_*eak 5

是的你可以.它们被称为转换运算符:

struct FancyDouble
{
    // your things here
    operator double() { return this->value; }
};
Run Code Online (Sandbox Code Playgroud)

您可以转换为任何类型,而不仅仅是内置类型.它们通常也被标记const(虽然我没有在这里做它以显示核心概念).

请注意,你的结构(如图所示)并不完全允许隐式转换doubleFancyDouble; 你operator=唯一的意思是你可以在赋值的右侧使用double,但是如果你有一个FancyDouble函数参数,它将无法工作,因为你需要的是一个接受double的构造函数,而不是赋值运算符.

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
Run Code Online (Sandbox Code Playgroud)

你会做这样的事情:

struct FancyDouble
{
    // your things here
    FancyDouble(double d) { /* initialization here */ }
};
Run Code Online (Sandbox Code Playgroud)

有了这个,你只需要一个operator=接受a FancyDouble而不是a double,转换将自动完成:

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
Run Code Online (Sandbox Code Playgroud)