The explicit keyword is in C + + to prevent an implicit conversion
(1)
Explicit
This keyword can only work on the user's own defined object, not the default constructor
This keyword can only decorate constructors. And the constructor parameter can only have one:
(2) When to use explicit
When we do not want to use the automatic type conversion, in fact, the standard library a lot of constructors are explicit
such as vectors <int> Ivec (10); This definition looks at a glance
cannot be written as vector <int> ivec=10;//This definition makes the programmer wonder
(3) when not to explicit
When we need an implicit conversion,
For example, a constructor for a string class
String (const char*);
This is defined as the benefit of the compiler automatically helping us to convert when implicit conversions are required, and the string in the standard library is a good proof.
Specifically:
We can do this by string str= "HelloWorld";//Call constructor directly
String str= "Hello" +str+ "world";
Call the overloaded + action symbol, which is equivalent to:
String temp ("Hello"); Call constructor
String Str=temp+str;
String T ("World");//Call constructor
String str=str+t;
It is useful to understand implicit conversions when we write our own classes, especially when manipulating memory classes.
Explicit keywords in C + +