static_cast、dynamic_cast、reinterpret_cast、const_cast以及C强制类型转换的区别

static_cast

1. 基础类型之间互转。如:float转成int、int转成unsigned int等

2. 指针与void*之间互转。如:float*转成void*、CBase*转成void*、函数指针转成void*、void*转成CBase*等

3. 派生类指针【引用】转成基类指针【引用】。如:Derive*转成Base*、Derive&转成Base&等

4. 非virtual继承时,可将基类指针【引用】转成派生类指针【引用】(多继承时,会做偏移处理)。如:Base*转成Derive*、Base&转成Derive&等

dynamic_cast  专门用于处理多态机制,对继承体系内的对象(类中必须含有至少一个虚函数)的指针【引用】进行转换,转换时会进行类型检查;vc在编译时要带上/EHsc /GR

如果能转换会返回对应的指针【引用】;不能转换时,指针会返回空,引用则抛出std::bad_cast异常(const std::bad_cast& e)

注:由于std::bad_cast类型定义在typeinfo头文件中,固需要#include<typeinfo>

另外,对于菱形非virtual继承、非public继承,转换引用时也会抛出std::bad_cast异常

reinterpret_cast  对指针【引用】进行原始转换,不做任何偏移处理(当然:多继承时,也不会做偏移处理)

1. 将指针【引用】转换成整型。如:float*转成int、CBase*转成int、float&转成int、CBase&转成int等

float f1 = 1.0f; CBase o1;
int n1 = reinterpret_cast<int>(&f1);
int n2 = reinterpret_cast<int>(&o1);
int n3 = reinterpret_cast<int&>(f1);
int n4 = reinterpret_cast<int&>(o1);

2. 指针【引用】之间互转。如:float*转成int*、CBase&转成int&、CBase*转成CBase2*、CBase&转成CBase2&等

float f1 = 1.0f;  CBase1 o1;
int* n1 = reinterpret_cast<int*>(&f1);
int& n2 = reinterpret_cast<int&>(o1);
CBase2* o21 = reinterpret_cast<CBase2*>(&o1);
CBase2& o22 = reinterpret_cast<CBase2&>(o1);

const_cast   去掉或增加const、volatile特性

C类型强制转换   形式:(type)object或type(object)

最好是使用type(object);原因是:在某些编译器下,(type)object不会调用构造函数,而type(object)下则肯定会调用构造函数

C类型强制转换会按照以下顺序进行尝试转换:

a. const_cast
b. static_cast
c. static_cast, then const_cast
d. reinterpret_cast
f. reinterpret_cast, then const_cast

 

参考:

https://www.cnblogs.com/kekec/p/3643578.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值