C++类型转换详解

1、C语言的隐式转换和显式转换

 double a=1.234;
 int b=(int)a;//强制转换

2、C++的类型转换运算符

1)static_cast(expr):
用于以下三种情况:
相关类型转换,例如整型、实型
子类转父类
void *与其他类型转换

//static_cast<T>(expr)
//相关类型转换
double b=1.23;
int a=static_cast<int>(b);
char c=static_cast<char>(b);

//void *与其他类型转换(单向)
int *pa=&a;
void *p=pa;//void*是万能指针,可以接受任何指针的类型 ,编译器不会报错
int *p2=p;//这句是错误的,不能把void*类型的指针转为int*型指针
int *p2=(int)p;//这样才是对的
//使用static_cast就可以把void*型指针转换为int*型指针
int *pa2=static_cast<int *>(p);

//static_cast:不允许指针之间类型转换
char *pc=&ch;
int *pa3=static_cast<int *>(pc);//错误!!!

2)reinterpret_cast(expr)
可以实现无关类型之间的转换

char *pc=&ch;
int *pa3=reinterpret_cast<int *>(pc);//相当于C语言,无关类型之间转换

int a=3;
float b=reinterpret_cast<float>(a);//错误,这是相关类型的转换

3)const_cast(expr)
去除指针和引用的const属性(其他类型是允许const赋值给非const)

const int *p=&a;
int *p2=p;//不可以把const指针转换为int*
int *p3=const_cast<int *>(p);

const int &la=a;
int &la2=la;//不可以把引用转换为int*
int &la3=const_cast<int &>(la);

4)dynamic_cast(expr)运行时类型识别与检查,用于父类子类之间的转换

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值