The explicit keyword in C ++ 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;
All the operations above 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 "display", that is, add the explicit it before declaring the constructor, this will prevent this automatic conversion operation. If we modify the above myclass constructor to display, the following code cannot be compiled, as shown below:
Class myclass
...{
Public:
Explicit myclass (INT num );
}
....
Myclass OBJ = 10; // err, can't non-explict convert