Many important keywords in the C ++ programming language play a very important role in actual programming. The C ++ explicit keyword we introduced today is one of the most frequently used keywords. Let's take a look at this knowledge.
The C ++ explicit keyword is used to modify the class constructor, indicating that the constructor is explicit. Since there is an "Explicit", there must be "implicit ", so what is explicit and what is implicit?
If the constructor of the C ++ class has a parameter, a default conversion operation will be performed during compilation: Convert the data of the corresponding data type of the constructor to this type of object, as shown below:
- class MyClass
- {
- public:
- MyClass( int num );
- }
- //.
- MyClass obj = 10; //ok,convert int to MyClass
In the code above, the compiler automatically converts an integer to a myclass object, which is actually equivalent to the following operation:
- MyClass temp(10);
- MyClass obj = temp;
The operations related to all the above C ++ explicit it keywords are called "implicit conversions ".
What should we do if we want to avoid this automatic conversion function? Hey, this is the role of the keyword explicit. Declare the class constructor as "Explicit", that is, add the explicit it before declaring the constructor, this will prevent this automatic conversion operation. If we modify the constructor of the above myclass class to be explicit, the following code will not be able to be compiled, as shown below:
- class MyClass
- {
- public:
- explicit MyClass( int num );
- }
- //.
- MyClass obj = 10; //err,can't non-explict convert
The preceding section describes the C ++ explicit keywords.