加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c中隐式转换的复制初始化

发布时间:2020-12-16 03:34:46 所属栏目:百科 来源:网络整理
导读: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'
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;
}

为什么第二个表达式无法编译?我希望它会调用与第一个表达式相同的转换构造函数.

解决方法

来自[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),它没有浮动.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读