By default, a constructor of only one parameter also defines an implicit conversion that converts data of the data type of that constructor to that class object, as follows:
[CPP]View Plaincopy
- Class String
- {
- String (const char* p) //with C-style string p as the initial value
- //........
- }
- String S1 = "Hello"; //ok, implicit conversion, equivalent to string s1 = string (' Hello ')
However, there may be times when this implicit conversion is not required, as follows:
[CPP]View Plaincopy
- Class String
- {
- string (int n) //intended to be pre-allocated n bytes to a string
- String (const char* p); //Use C-style string p as the initial value
- //........
- }
The following two types of notation are normal:
[CPP]View Plaincopy
- String S2 (10); //ok, which is an empty string that allocates 10 bytes
- String s3 = String (10); //ok, which is an empty string that allocates 10 bytes
But here are two ways to make us wonder:
[CPP]View Plaincopy
- String S4 = 10; //Compile through, that is, allocate 10 bytes of empty string
- String S5 = ' a '; //Compile through, allocate an empty string of int (' a ') bytes
S4 and S5, respectively, are an int and char, implicitly converted to an empty string that allocates several bytes, which is easily misleading.
To avoid this error, we can declare the transformation shown, that is, using the explicit keyword:
[CPP]View Plaincopy
- Class String
- {
- <span style="color: #cc0000;" >explicit</span> string (int n) //intended to be pre-allocated n bytes to a string
- String (const char* p); //Use C-style string p as the initial value
- //........
- }
The implicit conversion of string (int n) is suppressed by adding explicit.
The following two types of notation are still correct:
[CPP]View Plaincopy
- String S2 (10); //ok, which is an empty string that allocates 10 bytes
- String s3 = String (10); //ok, which is an empty string that allocates 10 bytes
However, the previous two formulations cannot be compiled, for example:
[CPP]View Plaincopy
- String S4 = 10; //compilation does not pass, implicit conversions are not allowed
- String S5 = ' a '; //compilation does not pass, implicit conversions are not allowed
So at some point, explicit can effectively prevent errors or misunderstandings caused by implicit conversions of constructors.
For example, further explanation:
explicit only works on constructors to suppress implicit conversions , as follows:
[CPP]View Plaincopy
- Class A
- {
- A (int a);
- };
- int Function (a a);
When function (2) is called, it is implicitly converted to type A. This situation is often not the result we want, so to avoid this situation, we can write:
[CPP]View Plaincopy
- Class A
- {
- explicit A (int a);
- };
- int Function (a a);
Thus, when the function (2) is called, the compiler gives the wrong information (unless the function has an overloaded form with an int parameter), which avoids errors that we do not know about.
Explicit constructor (display constructor)