C++ type conversion

content

1. Type conversion in C language

2. Why does C++ need four type conversions?

3.C++ forced type conversion


1. Type conversion in C language

When the left and right types of the operator are different, type conversion is required. The C language has two types of type conversions: implicit type conversions and explicit type conversions .

Implicit type conversion is performed automatically by the compiler during the compilation phase.

Display type conversion needs to be handled by the programmer himself.

int main()
{
    //隐式类型转换
    int i = 1;
    double d = i;
    printf("%d,%.2f\n",i,d);

    // 显示的强制类型转换
    int* p = &i;
    int address = (int) p;
    printf("%x, %d\n" , p, address);
}

2. Why does C++ need four type conversions?

The conversion style of the C language is simple, but has the following disadvantages.

Implicit type conversions may result in a loss of precision, revealing that the type conversion code is not clear enough.

Therefore, C++ proposes its own type conversion style, and C++ is compatible with the C language.

3.C++ forced type conversion

To enhance the visibility of type conversions, C++ introduces four named coercion operators.

static_cast、reinterpret_cast、const_cast、dynamic_cast

static_cast

//static_cast用于非多态类型的转换(静态转换),编译器隐式执行的任何类型转换都可用static_cast,但它不能用于两个不相关的类型进行转换
int main()
{
    double d = 3.14;
    int a = static_cast<int>(d);
    cout<<a<<endl;
    return 0;
}

reinterpret_cast

reinterpret_cast操作符通常为操作数的位模式提供较低层次的重新解释,用于将一种类型转换为另一种不同的类型

const_cast

const_cast常用的用途就是删除变量的const属性,方便赋值
int main()
{
    const int a = 2;
    int* p = const_cast<int*>(&a);
    *p = 3;
    cout<<a<<endl;
}

dynamic_cast

dynamic_cast用于将一个父类对象的指针/引用转换为子类对象的指针或引用(动态转换)
注意: 1. dynamic_cast只能用于含有虚函数的类 2. dynamic_cast会先检查是否能转换成功,能成功则转换,不能则返回0
class A
{
public :
virtual void f(){}
};
class B : public A
{};
void fun (A* pa)
{
// dynamic_cast会先检查是否能转换成功,能成功则转换,不能则返回
B* pb1 = static_cast<B*>(pa);
B* pb2 = dynamic_cast<B*>(pa);
cout<<"pb1:" <<pb1<< endl;
cout<<"pb2:" <<pb2<< endl;
}
int main ()
{
A a;
B b;
fun(&a);
fun(&b);
return 0;
}

Guess you like

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