1 -- problems caused by implicit type conversion
First, let's take a look at the example below. It can be compiled or executed, and the final result is "tdemo: Print 55 ". It is reasonable to infer that when an object is instantiated, the compiler automatically converts the integer 55 to "class tdemo ". The tdemo class defines a single parameter constructor. In the C ++ standard, the "single parameter constructor can complete an implicit conversion from the form parameter to the type ", therefore, the compiler can convert the int type to the tdemo type.
# Include <iostream> class tdemo {public: tdemo (INT num); void print () const {STD :: cout 2 -- disable implicit type conversion call "tdemo = 55" is actually "tdemo demo = tdemo (55)". The Compiler implicitly calls a single parameter constructor to generate a temporary tdemo object, then copy the temporary object to the demo variable. Sometimes we do not want the compiler to conceal us. To do this implicit conversion, we need Program Explicit conversions are clearly used. The written procedures are simple and clear, and many ambiguities and errors caused by implicit conversions can be avoided. In this case, you can use the keyword "Explicit" to disable the use of a single parameter constructor in the context that requires implicit conversion.
Modify the program in the preceding example. The single-parameter constructor uses explicit to modify it. After the program is compiled again, an error is displayed: "error: conversion from 'int' to non-scalar type 'tdemo' requested ", which disables implicit type conversion. # include
class tdemo {public: explicit tdemo (INT num); void print () const {STD :: cout 3 -- considerations when using the explicit keyword can only be used in the constructor declaration within the class, and does not repeat the definition made outside the class definition body. That is, the following two methods are both incorrect:
class tdemo {public: tdemo (INT num) ;}; // error: only declarations of constructors can be 'explicit' explicit tdemo: tdemo (INT num): I _num (Num) {}
class tdemo {public: explicit tdemo (INT num) ;}; // error: only declarations of constructors can be 'explicit' explicit tdemo: tdemo (INT num): I _num (Num) {}