C ++ four types of conversion

1. static_cast

Supports only the relevant type of conversion, relatively safe, such as short and int, double and int, void * and int *, float *, etc.

Features: Convert during compilation

 

2. const_case

Const expression modifications or remove volatile modification, the const / non-volatile type conversion const / volatile type, such as:

const int n = 100;
int *p = const_cast<int*>(&n);
*p = 234;

Int n where the original memory is a non-modifiable integer value, now it

If the output n, its value is 100, since similar #define const, proceeds in constant replacement of the!

 

3. reinterpret_cast

Static_cast is a supplement to achieve different types of conversions, the higher the risk,

Such as int pointer conversion, two types of pointers A * and B * conversion ...... careless use can cause access violation!

 

4. dynamic_cast

Class inherits only used when a pointer conversion between, and preferably up upcasting inherited, such as:

Derived *pD = new Derived(6);
Base *pB = dynamic_cast<Base*> (pD);

 

to sum up:

static_cast most common and relatively safe, reinterpret_cast cast unsafe, used with caution,

const_cast only used to const type variable, dynamic_cast process only for inherited classes.

Guess you like

Origin www.cnblogs.com/Younger-Zhang/p/12132138.html