mardi 2 février 2021

Direct initialization gives an error when initializing class types

 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

The std says that in direct initialization an implicit conversion to one of the T argument's constructor is applicable. Why the second initialization with two arguments throws an error?

Aucun commentaire:

Enregistrer un commentaire