C++ implicit type conversion, explicit type conversion (mandatory type conversion)

  1. Implicit type conversion
    1. When two variables of different types are operated, such as

    int a=1;
    double b=3.0;
    double c = a+b; //会把int转换成double再运算
    

    2. When the expression return type is different, or the function return type is different

    int a = 3.6+2.3;
    

    For example, the return type of a function is Int, but if you return a double type, it will be implicitly converted to int for you

  2. Mandatory type conversion
    1, C style (commonly used)
    the type inside the brackets, or the data inside the brackets

    int a=6;
    //下面两种都行,都是C方式
    double b = double(a) * 2;
    double c = (double)a * 3;
    

    2. C++ mandatory type conversion (4 types)
    (1) static_cast<>() Static conversion, completed at compile time (recommended)

    int a=10;
    double b = static_cast<double>(a) * 3;
    

    It can be used to convert ordinary variables above, cast subclasses to parent classes, and convert void* type pointers to other types of pointers
    (2) dynamic_cast<>(): The operation is to check the conversion, and the parent class can be converted to a subclass, and the conversion cost Very large
    (3) const_cas<>()t: Remove the const attribute of pointers and references , and can remove the const attribute

    const int* p1;
    int* p2 = const_cast<int*>(p1);
    

    (4) reinterpret_cast<>()
    can even convert between different types, turn int into pointer, and turn int pointer into double pointer, which is very dangerous and should be used less

Guess you like

Origin blog.csdn.net/qq_41253960/article/details/124391737