在 C++ 中使用隐式转换进行复制初始化

Copy-initialization with implicit conversion in c++

class Foo {
  public:
    Foo(float b) {}
};

class Bar {
  public:
    Bar(Foo foo) {}
};

int main(int argc, char *argv[]) {
    Bar b1(3.0f);  // accept, one implicit convertion happens there.
    Bar b2 = 3.0f;  // error: no viable conversion from 'float' to 'Bar'
    return 0;
}

为什么第二个表达式编译失败?我预计它会调用与第一个表达式相同的转换构造函数。

第二种初始化称为复制初始化,使用复制构造函数。因此,这种类型的初始化期望右侧可转换为 Bar。

来自[dcl.init]:

Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3).

我们可以调用从源类型直接到目标类型的用户定义转换。也就是说,如果我们有 Bar(float ),我们会考虑该构造函数。然而,在这种情况下,我们的候选人只是 Bar(Foo ),它不需要 float

您可以进行零次或一次用户定义的转换。在直接初始化的情况下,我们只需调用 Bar(Foo ) 即可调用一个用户定义的转换 (float --> Foo)。在复制初始化的情况下,我们正在寻找从 float(源类型)一直到 Bar(目标类型)的转换序列,这将涉及 two 用户定义的转换(float --> FooFoo --> Bar),因此出现错误。