Conversion constructor in C++

In C/C++, different data types can be converted to each other. The type that does not require the user to specify how to convert is called automatic type conversion (implicit type conversion), and the type that requires the user to explicitly specify how to convert is called forced type conversion.

Automatic type conversion example:

    int a = 6;
    a = 7.5 + a;

The compiler treats 7.5 as a double type. When solving the expression, it first converts a to a double type, and then adds it to 7.5 to obtain a sum of 13.5. When assigning a value to the integer variable a, convert 13.5 into the integer 13 and then assign it to a. During the whole process, we did not tell the compiler how to do it. The compiler used built-in rules to complete the data type conversion. Example of cast:

    int n = 100;
    int *p1 = &n;
    float *p2 = (float*)p1;

p1 is int *a type, the memory it points to stores an integer, p2 is float *a type, after assigning p1 to p2, p2 also points to this memory, and treats the data in this memory as a decimal. We know that the storage formats of integers and decimals are very different. It is absurd to treat integers as decimals and may cause inexplicable errors. Therefore, the compiler does not allow p1 to be assigned to p2 by default. However, by using a cast, the compiler assumes that we are aware of the risk.

Supongo que te gusta

Origin blog.csdn.net/shiwei0813/article/details/133047943
Recomendado
Clasificación