1.9 C++ different data type conversion

C++ different data type conversion

In C++, data conversion between different types can be achieved through mandatory type conversion (type conversion operator).

There are three types of mandatory conversion in C++:

1、static_cast

static_cast can be used for conversions between primitive data types, as well as for downcasts (conversion of derived class pointers to base class pointers) and upcasts (conversion of base class pointers to derived class pointers) in class hierarchies.
insert image description here
static_cast can convert an expression to a certain type, but it does not guarantee the safety of the conversion, so it is up to the programmer to judge whether the conversion is legal.

2、dynamic_cast

dynamic_cast is mainly used for downcasting in the class hierarchy, the conversion of derived class pointers to base class pointers.
insert image description here
dynamic_cast can convert a base class pointer or reference to a derived class pointer or reference, and return the converted pointer or reference if the conversion is successful, otherwise return nullptr.

dynamic_cast can only be used for classes with virtual functions, because the conversion process needs to use virtual tables to determine the type of the object.

3、reinterpret_cast

reinterpret_cast can convert a pointer or reference to another pointer or reference, but it cannot change the object pointed to by the pointer or reference, only the type of the pointer or reference.

reinterpret_cast can be used for conversion between any types, but the safety of the conversion needs to be judged by the programmer.
insert image description here
Readers should note that mandatory type conversion should be used with caution, because it is likely to cause problems such as type errors and memory errors.

When using forced type conversion, be sure to check the code logic carefully to ensure the safety of the conversion.

Guess you like

Origin blog.csdn.net/qq_40240275/article/details/131243451