By Default, a constructor with only one parameter also defines an implicit conversion that converts data of that constructor's data type to that class object , as shown here:Class String {string (const char* p);//C-style string p as initialization 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:Class String {string (int n);//is intended to be pre-allocated n bytes to string strings (const char* p);//with C-style string p as initialization value//...} The following two kinds of notation are more normal: string S2 (10); OK allocates an empty string of 10 bytes s3 = string (10); OK allocates 10 bytes of empty string The following two kinds of writing are more doubtful: string s4 = 10; Compiled by, is also a 10-byte empty string that is assigned string s5 = ' a '; Compiled by, an empty string that allocates an int (' a ') byte, S4 and S5, respectively, converts an int and char, implicitly to an empty string that allocates several bytes, which is easily misleading. In order to avoid this error, we can declare the transformation shown, using the
ExplicitKeyword: class String {
ExplicitString (int n); The intent is to pre-allocate n bytes to string strings (const char* p); Use C-style string p as initialization value//...} Plus
Explicit
,The implicit conversion of string (int n) is suppressed, and the following two types of notation are still correct: string S2 (10); OK allocates an empty string of 10 bytes s3 = string (10); OK allocates 10 bytes of empty string The following two kinds of notation are not allowed: string s4 = 10; The compilation does not pass and does not allow the implicit conversion of 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 conversion of constructors
----------------------------------------------------------
Explicit only works on constructors to suppress implicit conversions. Such as:
Class A {
A (int a);
};
int Function (a a);
When Function (2) is called, 2 is implicitly converted to type A. This situation is often not the result that programmers want, so to avoid it, you can write:
Class A {
Explicit a (int a);
};
int Function (a a);
Thus, when the function (2) is called, the compiler gives an error message (unless the function has an overloaded form with an int parameter), which avoids errors without the programmer's knowledge.
Summary: Explicit only works on constructors to suppress implicit conversions.
Reference:
Http://blog.csdn.net/smilelance/archive/2007/03/14/1528737.aspx
Http://topic.csdn.net/t/20040509/15/3046021.htmltransferred from: http://www.cnblogs.com/cutepig/archive/2009/01/14/1375917.html
C + + Explicit keywords