0
 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 参数的构造函数之一是适用的。为什么带有两个参数的第二次初始化会引发错误?

4

1 回答 1

0

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

 Spaceship(int number, char const* name){
   alien1.id = number;
   alien1.name = name;
};
于 2021-02-02T15:53:47.837 回答