C++ Type Conversion Explained



The basic types in the c language, char, short, int, uint, long.ulong, float, double, they have implicit type conversions in expressions. When performing operations, they are converted to the largest type of rvalue by default, and then Operation, after the result is obtained, the type of lvalue is forced to be assigned to the lvalue. During the period, char and short must be converted to int type first, and the unsigned in the basic type is greater than the signed. This relationship is also satisfied in C++, but now there are classes, how to convert classes and basic data types.

If the basic data type wants to be converted into a class type, a conversion constructor is required. The conversion constructor has only one parameter, and the type of the parameter is the basic type or other class type. If our parameter is a basic data type, then as long as the data of the basic type will be cast to the value of this type and then call a conversion constructor to complete the conversion of the basic data type to the class type. Because the type of the parameter can be of other class types, all can also complete type-to-type conversion.

If the class type is converted into a basic data type, a type conversion function is required, and the function of Type operator Type(){} needs to be implemented by yourself. This function can also perform type-to-type conversions.

Both are called automatically, and both can complete the conversion between class types, so if the two classes, the class type of the rvalue has a type conversion function, and the class type of the lvalue has a conversion constructor, there will be ambiguity. Also, when the conversion constructor of a class type is a basic type, it will not only be called automatically but also has implicitly typed C language conversion. What if we want to avoid the above two situations?

For the latter, we can use the conversion constructor An explicit keyword is added before the function to tell the compiler not to automatically call the conversion constructor, but to allow the user to display the call. In this way, although we have not completely solved the mutual conversion between basic data types, we prompt the user to consider whether to use this conversion constructor by explicitly calling this function.

For the former, we have two methods, one is to use the keyword explicit for the conversion constructor, so that the compiler can no longer automatically call the type conversion function, all can only call the conversion constructor, and the other, in order to avoid the type conversion function is also automatically called We usually do not use the type conversion function, but provide the member function of toType() in the member method of the class to complete the type conversion function.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326472508&siteId=291194637