c++ 中几种转换

在C语言中转换的意义是:编译器你把XXX看做这个类型
这样会带来不安全,所以C++中改良转换,并且提供四个关键字:

static_cast
基本上的功能是和c的转换一致(编译器你把XXX看做这个类型),但是功能有所弱化,例如:不能把指针转化成int 型。

1。The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class.(类的指针转换)
注:在有类的继承关系时,static_cast根据 移指针的方式来确定子类中包含的父类的指针(Com中的应用原理在此),因为编译器有足够的信息知道子类中父类的指针在哪儿。

2。In general you use static_cast when you want to convert numeric data types such as enums to ints or ints to floats, and you are certain of the data types involved in the conversion.(基本数据类型之间的转换)

const_cast
把const转换成非const,但是只能是转换到相应类型的非const类型
把volatile转换成非volatile,可以不必转换成相应类型的volatile


dynamic_cast

利用RTII功能在运行时检查指针类型,也就是说在类的指针向下转换时它时安全的,它能识别类型。转换成功返回相应指针,否则返回0


reinterpret_cast

就是重新解释类型的意思

The reinterpret_cast operator allows any pointer to be converted into any other pointer type. It also allows any integral type to be converted into any pointer type and vice versa.

从指针 到 整形  ok
从整形 到 指针  ok

从指针 到 指针  ok

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值