1) C++ type conversion is divided into two types, one is implicit conversion and the other is explicit conversion.
2) C++ should try not to use conversion, try to use explicit conversion instead of implicit conversion .
1 implicit conversion
Definition: Implicit conversion is automatically converted by the system according to the needs of the program.
1) Implicit conversion of C++ types (char, int, float, long, double, etc.):
The order of implicit conversion of arithmetic expressions is:
1、char - int - long - double
2、float - double
//1) Arithmetic expression int m = 10; double n = m; //n = 10.0; implicitly convert m to double type int m = 10; float f = 10.0; double d = m + f;// n = 20.0; implicitly convert m and f to double type //2) assign int *p = NULL; //NULL(0) is implicitly converted to a null pointer value of type int* //3) function enters float add(float f); add(2); //2 implicit conversion to float type //4) function return value double minus(int a, int b) { return a-b; //return value implicit conversion to double type }
2) Implicit conversion of C++ class objects:
void fun(CTest test); class CTest { public: CTest(int m = 0); } fun(20);//Implicit conversion
2 Explicit conversion
Definition: Explicit conversion is also called coercion, which is to convert this type to another type on its own initiative.
1) Explicit conversion of C++ types (char, int, float, long, double, etc.):
int m = 5; char c = (char)m;//Explicitly convert m to char type double d = 2.0; int i = 1; i += static_cast<int>( d);//Explicitly convert d Convert to int type
2) Explicit conversion of C++ class objects: When the class constructor has only one parameter or the rest of the parameters except the first parameter have default values, this class has an implicit type conversion operator (implicit conversion), but Sometimes implicit conversion is not what we want, you can add the keyword explicit before the constructor to specify an explicit call.
void fun(CTest test); class CTest { public: explicit CTest(int m = 0); } fun(20);//error implicit conversion fun(static_cast<CTest>(20)); //ok explicit conversion