Description:
In C ++, the explicit keyword is used to modify the constructor of a class. The class of the constructor to be modified cannot undergo corresponding implicit type conversion. type conversion can only be performed in display mode.
Note:
*
The explicit keyword can only be used in the constructor declaration within the class.
*
The explicit keyword acts on the constructor of a single parameter.
* In C ++, the explicit keyword is used to modify the class constructor. The class of the constructor to be modified cannot undergo corresponding implicit type conversion.
Example:
Implicit type conversion without explicit
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;
10. Int y;
11 .};
12.
13. Int _ tmain (INT argc, _ tchar * argv [])
14 .{
15. // implicit type conversion
16. // the compiler will convert it into the following code:
17. // TMP = circle (1.23)
18. // Circle A (TMP );
19. // TMP .~ Circle ();
20. Circle A = 1.23;
21. // note that it is of the int type. It calls circle (int x, int y = 0)
22. // although it has two parameters, the latter has a default value and can still be implicitly converted.
23. Circle B = 123;
24. // This operation implicitly calls the copy constructor.
25. Circle C =;
26.
27. Return 0;
28 .}
After the explicit it keyword is added, the above implicit type conversion can be prevented.
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;
10. Int y;
11 .};
12.
13. Int _ tmain (INT argc, _ tchar * argv [])
14 .{
15. // an error will be reported in three sentences
16. // Circle A = 1.23;
17. // circle B = 123;
18. // Circle C =;
19.
20. // It can only be called in display mode.
21. // you can do this before adding an explicit statement to the copy constructor.
22. Circle A = circle (1.23 );
23. Circle B = circle (123 );
24. Circle C =;
25.
26. // This is the only way to do this after an explicit statement is added to the copy constructor.
27. Circle A (1.23 );
28. Circle B (123 );
29. Circle C ();
30. Return 0;
31 .}