微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

初始化类类型时直接初始化会报错

如何解决初始化类类型时直接初始化会报错

 struct Alien {
    int id;
    char const* name;
    Alien() = default;
    Alien(int id,char const* name) : id{id},name{name} {}
    Alien(int id): id{id} {}
 };

 struct Spaceship {
    Alien alien1;
    Spaceship() = default;
    Spaceship(Alien const& z) {}
    Spaceship(Spaceship const& other) = default;
    Spaceship(Spaceship&& other) = default;
};

int main()
{
   Spaceship s1(3433); // works
   Spaceship s2(2322,"Kronas"); // error
}

source>:55:14: error: no matching constructor for initialization of 'Spaceship'
   Spaceship s(2322,"Kronas");
             ^ ~~~~~~~~
<source>:45:5: note: candidate constructor not viable: requires single argument 'z',but 2 arguments were provided
    Spaceship(Alien const& z) { }
    ^
<source>:46:5: note: candidate constructor not viable: requires single argument 'other',but 2 arguments were provided
    Spaceship(Spaceship const& other) = default;
    ^
<source>:47:5: note: candidate constructor not viable: requires single argument 'other',but 2 arguments were provided
    Spaceship(Spaceship&& other) = default;
    ^
<source>:44:5: note: candidate constructor not viable: requires 0 arguments,but 2 were provided
    Spaceship() = default;
    ^
1 error generated.
Execution build compiler returned: 1

std 说在直接初始化中,隐式转换到 T 参数的构造函数之一是适用的。 为什么带有两个参数的第二次初始化会抛出错误

解决方法

没有一个 Spaceship 构造函数接受两个参数。这就是为什么当你给它两个时它会抛出错误。应该是这样的:

 Spaceship(int number,char const* name){
   alien1.id = number;
   alien1.name = name;
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。