Read a book see explicit key words, to make a note, speak more clear, relatively shallow.
In C + +, we can sometimes use constructors as automatic type conversion functions. However, this automatic feature is not always desirable and sometimes results in unexpected type conversions, so C + + has a new keyword explicit to turn off this automatic feature. That is, the class constructor that is decorated with the explicit keyword, cannot be automatically implicitly type-converted, and can only be explicitly type-cast.
Note: The constructor for only one parameter, or the constructor has n parameters, but there are n-1 parameters that provide the default value for the type conversion.
Here's a code to illustrate the application (no explicit scenario):
1 /*Example code 1*/2 classDemo3 {4 Public:5 Demo (); / * Constructor 1 * /6Demo (Doublea); / * Sample code 2 * /7Demo (intADoubleb); / * Sample Code 3 * /8Demo (intAintb=Ten,DoubleC=1.6); / * Sample code 4 * /9~Demo ();Ten voidFunc (void); One A Private: - intvalue1; - intvalue2; the};
These four constructors:
Constructor 1 does not have parameters and cannot be converted by type!
Constructor 2 has a parameter that can be converted to type, such as: Demo test; Test = 12.2; Such a call would be equivalent to converting 12.2 implicitly to the demo type.
Constructor 3 has two parameters and no default value, so type conversion cannot be used!
Constructor 4 has 3 parameters, of which two parameters have default values, it can be implicitly converted, such as: Demo test;test = 10; 。
Here's what happens when you use the keyword explicit:
1 1 /*Example code 2*/2 2 classDemo3 3 {4 4 Public:5 5Demo ();/*Constructor 1*/6 6 ExplicitDemo (Doublea);/*Example code 2*/7 7Demo (intADoubleb);/*Example Code 3*/8 8 9 9~Demo ();Ten Ten voidFunc (void); One One A A Private: - - intvalue1; - - intvalue2; the the};
In the above constructor 2, implicit conversions cannot be made because the explicit keyword is used. That is: Demo test;test = 12.2; is invalid! But we can do display type conversions, such as:
Demo test;
Test = Demo (12.2); Or
Test = (Demo) 12.2;
Use of explicit keywords in C + +