C++强制类型转换

强制类型转换

静态转换(static_cast)

动态转换(dynamic_cast)

常量转换(const_cast)

重新解释转换(reinterpret_cast)


静态转换(static_cast)

用于基础类型转换

如把int转换成char。这种转换的安全也要开发人员来保证

  char a = 'a';
  double d = static_cast<double>(a); //char->double
类层次结构中基类和派生类之间指针或引用的转换
进行上行转换(把派生类的指针或引用转换成基类表示)是安全的

进行下行转换(把基类的指针或引用转换成派生类表示),由于没有动态类型检查,是不安全的
指针转换
//father 为基类 son 为派生类
father *f = NULL;
son *s = NULL;
son *s1 = static_cast<son *>(f);//向下转换 不安全
father *f1 = static_cast<father *>(s);//向上转换,安全
//没有亲属关系不能转换
//other *o = static_cast<other>(s);
引用转换
father f;
son s;
father &ref_f = f;
son &ref_s = s;
static_cast<father &>(ref_s);//向上
static_cast<son &>(ref_f);//向下

还可以:

把空指针转换成目标类型的空指针

把任何类型的表达式转换为void类型

但不可以:

static_cast不能转换掉expression的const、volitale或者__unaligned属性

特点:

可以实现C++中内置基本数据类型之间的相互转换

只能在有相互联系的类型中进行相互转换

动态转换(dynamic_cast)

基础类型不能使用动态转换
//char a = 'a';
//dynamic_cast<double>(a); 基础类型不能使用动态转换
用于类层次间上行转换和下行转换
上行转换时,dynamic_cast和static_cast效果一样

下行转换时,dynamic_cast具有类型检查的功能,比static_cast安全
  father *f = NULL;
  son *s = NULL;
  father *f1 = dynamic_cast<father *>(s);
  //son *s1 = dynamic_cast<son *>(f); 向下不安全 检查 不通过编译
多态后可以向下转换(基类中要有虚函数)
class father2
{
public:
    virtual void func();
};
class son2 : public father2
{
public:
    virtual void func();
};
//发生多态时,向下转换
void test()
{
    father2 *f = new son2;
    dynamic_cast<son2 *>(f);
}

常量转换(const_cast)

去除常量性的对象必须为指针或引用。

常量指针/引用被转换成非常量指针/引用,并且仍然指向原来的对象

const int *p = NULL;
int *newp = const_cast<int *>(p); //const int* ->int *
int *pp = NULL;
const int *newpp = const_cast<const int *>(pp); //int* ->const  int *

不能对非指针和非引用的变量使用去除其const


重新解释转换(reinterpret_cast)

使用reinterpret_cast强制转换过程仅仅只是比特位的拷贝,因此在使用过程中需要特别谨慎,不安全

改变指针或引用的类型、将指针或引用转换为一个足够长度的整形、将整型转换为指针或引用类型。

int a = 10;
int *p = reinterpret_cast<int *>(a); //整数->指针
father *f = NULL;
other *o = reinterpret_cast<other *>(f); //father->other
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值