Explicit constructor and initialization with std :: initializer_list

class P { 
    public:
explicit P( int a, int b, int c) {  
    std::cout<<"calling explicit constructor"<<"\n";
    } 

};


int main() {

P z {77,5,42}; // OK

P w = {77,5,42}; // ERROR due to explicit (no implicit type conversion allowed)

}

I think it {77,5,42}has an implicit type std::initialization_list<int>. If so, then what does not cause a failure to build the variable z?

+4
source share
2 answers

I think it {77,5,42}has an implicit typestd::initialization_list<int>

{77,5,42}by itself has no type. If you write auto x = {77, 5, 42}, it xhas a type initializer_list. The type of your example Phas an explicit constructor. Effectively, this means you should write:

P w = P{77, 5, 42}

Or better:

auto w = P{77, 5, 42}

If so, then what does not cause a failure to build the variable z?

, : P x{a, b, c} , () P.

+3

, ,

= {77,5,42};

.

, , , . , .

: ++?

0

All Articles