浅析c++中的类型转换--reinterpret_cast
2015-10-14 23:35
288 查看
趁着热乎劲,把第四个C++中的类型转换符介绍完。
首先看一下reinterpret是什么意思?
reinterpret vt. 重新解释;
reinterpret_cast作用为:
允许将任何指针转换为任何其他指针类型。 也允许将任何整数类型转换为任何指针类型以及反向转换。
看着上面的描述就有种放浪形骸的赶脚。更会让人不寒而栗,太随意!
语法还是老样子:
reinterpret_cast < type-id > ( expression )
滥用 reinterpret_cast 运算符可能很容易带来风险。 除非所需转换本身是低级别的,否则应使用其他强制转换运算符之一。
reinterpret_cast 运算符可用于 char* 到 int* 或 One_class* 到 Unrelated_class* 之类的转换,这本身并不安全。
reinterpret_cast 的结果不能安全地用于除强制转换回其原始类型以外的任何用途。 在最好的情况下,其他用途也是不可移植的。
reinterpret_cast 运算符不能丢掉 const、volatile 或 __unaligned 特性。 有关移除这些特性的详细信息,请参阅 const_cast Operator。
r
einterpret_cast 运算符将 null 指针值转换为目标类型的 null 指针值。
reinterpret_cast 的一个实际用途是在哈希函数中,即,通过让两个不同的值几乎不以相同的索引结尾的方式将值映射到索引。(我也不懂,求指导)
msdn上给的代码:
总之,慎用!少用!
首先看一下reinterpret是什么意思?
reinterpret vt. 重新解释;
reinterpret_cast作用为:
允许将任何指针转换为任何其他指针类型。 也允许将任何整数类型转换为任何指针类型以及反向转换。
看着上面的描述就有种放浪形骸的赶脚。更会让人不寒而栗,太随意!
语法还是老样子:
reinterpret_cast < type-id > ( expression )
滥用 reinterpret_cast 运算符可能很容易带来风险。 除非所需转换本身是低级别的,否则应使用其他强制转换运算符之一。
reinterpret_cast 运算符可用于 char* 到 int* 或 One_class* 到 Unrelated_class* 之类的转换,这本身并不安全。
reinterpret_cast 的结果不能安全地用于除强制转换回其原始类型以外的任何用途。 在最好的情况下,其他用途也是不可移植的。
reinterpret_cast 运算符不能丢掉 const、volatile 或 __unaligned 特性。 有关移除这些特性的详细信息,请参阅 const_cast Operator。
r
einterpret_cast 运算符将 null 指针值转换为目标类型的 null 指针值。
reinterpret_cast 的一个实际用途是在哈希函数中,即,通过让两个不同的值几乎不以相同的索引结尾的方式将值映射到索引。(我也不懂,求指导)
msdn上给的代码:
#include <iostream> using namespace std; // Returns a hash code based on an address unsigned short Hash( void *p ) { unsigned int val = reinterpret_cast<unsigned int>( p ); return ( unsigned short )( val ^ (val >> 16)); } using namespace std; int main() { int a[20]; for ( int i = 0; i < 20; i++ ) cout << Hash( a + i ) << endl; } Output: 64641 64645 64889 64893 64881 64885 64873 64877 64865 64869 64857 64861 64849 64853 64841 64845 64833 64837 64825 64829
总之,慎用!少用!
相关文章推荐
- 浅析c++中的类型转换--reinterpret_cast
- C语言之typedef int (*funcptr)()
- C语言文件打开和二进制打开方式的区别
- C++学习笔记(第一篇)
- 浅析c++中的类型转换--const_cast
- 浅析c++中的类型转换--const_cast
- C++文件(夹)选择对话框
- 剑指offer第十一题【二进制中1的个数】c++实现
- 编写程序求解: 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?打印出来?
- c++ primer第五版(中文)习题答案 第十章第四节第三小节-反向迭代器
- C语言:在屏幕上打印杨辉三角形
- 编这样一个程序,用户输入10个整数,程序找出其中的最大值和最小值
- 从标准输入读取几行输入。每行输入都要打印到标准输出上,前面加上行号,使能够处理的输入行的长度没有限制
- 编写猜数字游戏
- 【面试题】C语言:根据A,B,C,D四人没人说得一句话,四句话仅有三句话正确,判断嫌疑犯
- [C++] Memory_stack_heap
- .编写折半查找函数。
- C++与JAVA的异同
- 打印杨辉三角问题
- C语言:5位运动员每人说了两句话,均有一句话正确,预测比赛结果