Many of the more important keywords in the C + + programming language play a very important role in practical programming. The C + + explicit keyword We've introduced to you today is one of the more frequently used keywords. Let's take a look at this knowledge together.
C + + Explicit keyword is used to decorate the constructor of the class, indicating that the constructor is explicit, since there is "explicit" then there must be "implicit", then what is the display and what is implicit?
If the constructor of a C + + class has a parameter, there is a default conversion operation at compile time: Convert the data of that constructor's data type to that class object, as shown here:
- Class MyClass
- {
- Public
- MyClass (int num);
- }
- //.
- MyClass obj = ten;//ok,convert int to MyClass
In the code above, the compiler automatically converts an integral type to an MyClass class object, which is actually equivalent to the following operation:
- MyClass Temp (10);
- MyClass obj = temp;
All of the above-mentioned C + + explicit keyword-related operations are called "implicit conversions."
What do we do if we want to avoid this kind of auto-conversion function? Hey, this is the keyword explicit, the constructor of the class is declared as "explicit", that is, when declaring the constructor is added before the explicit can be prevented, so as to prevent this automatic conversion operation, if we modify the above MyClass class constructor is explicit, Then the following code will not be able to compile through, as follows:
- Class MyClass
- {
- Public
- explicit MyClass (int num);
- }
- //.
- MyClass obj = ten;//err,can ' t non-explict convert
This article transferred from: http://developer.51cto.com/art/201002/183398.htm
How to apply C + + explicit keywords