C++ 四种类型转换

1. static_cast

只支持相关类型的转换,比较安全,比如short与int,double与int,void* 与 int*, float*等

特点:编译期间转换

2. const_case

去掉表达式的 const 修饰或 volatile 修饰,将 const/volatile 类型转换为非 const/volatile 类型,比如:

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

原来int n所在内存是一个不可修改值的整型,现在可以了

假如输出n,其值还是100,因为const类似#define,在常量期就进行了替换!

注意:

顶层const:指针本身是常量;

底层const:指针指向的对象是常量;

const_cast只能改变对象的底层const,也就是说,假如指针/变量本身是const类型,可以直接转化为普通指针或类型;

C++只限制指针指向常量时,const int* pInt -> int* pInt:

const int a = 1;
int b = a; //正确,借用a的值而非类型

int* const pInt3 = &a;
int* pInt4 = pInt3; //正确,pInt4是普通指针

const int* pInt = &a;
int* pInt1 = pInt; //错误,const int*转化为int*
int* pInt2 = const_cast<int*> (pInt); //正确,pInt2是普通指针

3. reinterpret_cast

是 static_cast 的一种补充,实现不同类型的转换,风险较高,

比如int与指针的转换,两个类型指针A*与B*的转换……使用不小心会导致访问越界!

4. dynamic_cast

只用来类继承的时候指针之间的转换,而且最好是向上继承upcasting,比如:

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

总结:

static_cast最常用而且比较安全,reinterpret_cast强制转换不安全,谨慎使用,

const_cast只用来处理const类型变量,dynamic_cast只用来处理类的继承。

原文地址:https://www.cnblogs.com/Younger-Zhang/p/12132138.html