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

问题描述

 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;
};