Source: http://www.cnblogs.com/this-543273659/archive/2011/08/02/2124596.html
Explicit effect:
In C + +, the explicit keyword is used to modify the constructor of a class, the class of a constructor that is decorated, the corresponding implicit type conversion cannot occur, and the type conversion can only be performed in a display way.
Explicit precautions for use:
*
The explicit keyword can only be used on a constructor declaration inside a class.
*
The explicit keyword is used as a constructor for a single argument.
* in C + +, the explicit keyword is used to modify the class's constructor, the class of the constructor being decorated, and the corresponding implicit type conversion cannot occur
Example:
Implicit type conversion when explicit is not added
1. Class Circle
2. {
3. Public:
4. Circle (Double R): R (r) {}
5. Circle (int x, int y = 0): x (x), Y (y) {}
6. Circle (const circle& C): R (C.R), X (c.x), Y (C.Y) {}
7. Private:
8. Double R;
9. int X;
int Y;
11.};
12.
int _tmain (int argc, _tchar* argv[])
14. {
15.//An implicit type conversion occurs
16.//The compiler will turn it into the following code
//tmp = Circle (1.23)
//circle A (TMP);
//tmp.~circle ();
Circle A = 1.23;
21.//Note is of type int, call circle (int x, int y = 0)
22.//Although it has 2 parameters, but the latter one has a default value, still can occur implicit conversion
Circle B = 123;
24.//This calculation implicitly calls the copy constructor
Circle C = A;
26.
. return 0;
28.}
When the explicit keyword is added, it prevents the above implicit type conversion from occurring
1. Class Circle
2. {
3. Public:
4. Explicit Circle (Double R): R (r) {}
5. Explicit Circle (int x, int y = 0): x (x), Y (y) {}
6. Explicit Circle (const circle& C): R (C.R), X (c.x), Y (C.Y) {}
7. Private:
8. Double R;
9. int X;
int Y;
11.};
12.
int _tmain (int argc, _tchar* argv[])
14. {
15.//3 sentences, will be an error
//circle A = 1.23;
//circle B = 123;
//circle C = A;
19.
20.//can only be called in the display mode
21.//Do not add explicit to the copy constructor.
Circle A = Circle (1.23);
Circle B = Circle (123);
Circle C = A;
25.
26.//Add explicit to the copy constructor only then.
Circle A (1.23);
Circle B (123);
Circle C (A);
0. return;
31.}
The role of C + + explicit