Chinaunix

标题: 标准C++类型转换-------高手进 [打印本页]

作者: csoftman    时间: 2012-05-22 10:55
标题: 标准C++类型转换-------高手进
本帖最后由 csoftman 于 2012-05-22 11:31 编辑

学习标准C++类型转换的时候,四种转换:
static_cast
dynamic_cast
const_cast
reindivter_cast
学习了一阵子了,还是糊里糊涂的,不清除具体的用法,求CU里C++高手给白话总结下这四个转换的用法,不要粘贴,网上帖子很多,我想要最精炼的总结!

不好意思写错了 是reinterpret_cast,高手过来总结下啊!
作者: csoftman    时间: 2012-05-22 10:56
自己顶个,不要沉了啊
作者: AD8018    时间: 2012-05-22 10:57
没有 reindivter_cast
作者: Moon_Bird    时间: 2012-05-22 11:12
reindivter_cast   ->   reinterpret_cast

作者: lsnl8480    时间: 2012-05-22 13:01
static_cast    基本类型间的转换
dynamic_cast    类族间的转换
const_cast    取消常量性的转换
reindivter_cast    看你写的这么随意,那这个就是随意转换吧。

作者: sonicling    时间: 2012-05-22 13:27
static_cast<T>(expr) 类似 (T)expr 的显式转换,但是不能用于
1. ptr/ref of derived class to ptr/ref of base class,
2. const to non-const, volatile to non-volatile
3. array to pointer,
4. function to pointer,
5. lvalue to rvalue

dynamic_cast<T>(expr) 主要用于 ptr/ref of derived class to ptr/ref of base class,不能用于
1. null pointer conversion
2. const to non-const, volatile to non-volatile
static_cast 限制里的3 - 5条应该也不准

const_cast<T>(expr) 主要用于 const to non-const, volatile to non-volatile,而且允许static_cast限制里的3 - 5.

reinterpret_cast<T>(expr) 与上面三个不同在于:它和(T)expr行为非常不同,它直接将内存区块按新类型解释,而且允许static_cast限制里的3 - 5.
作者: sonicling    时间: 2012-05-22 13:31
补充一点:reinterpret_cast先尝试进行
3. array to pointer,
4. function to pointer,
5. lvalue to rvalue
这三个转换,然后再重新解释。不能用于 const to non-const, volatile to non-volatile
作者: sonicling    时间: 2012-05-22 14:02
更正一下:

3. array to pointer,
4. function to pointer,
5. lvalue to rvalue

这三个转换是标准转换。任何必要的地方,标准转换都可以进行。

所以static_cast 和 const_cast都可以进行这三个转换
作者: shexinwei    时间: 2012-05-22 15:24
sonicling 发表于 2012-05-22 13:27
static_cast(expr) 类似 (T)expr 的显式转换,但是不能用于
1. ptr/ref of derived class to ptr/ref of  ...


:wink:
作者: rain_fish    时间: 2012-05-22 15:31
回复 1# csoftman


    去const用const_cast,否则就用static_const
作者: walleeee    时间: 2012-05-22 18:41
本帖最后由 walleeee 于 2012-05-22 18:42 编辑


来的看来都是高手
作者: _Rayx    时间: 2012-05-22 22:25
Effective C++里就讲得很详细了。建议看看。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2