reinterpret_cast的功能比static_cast的功能更为强大,但安全性也更为的差,可以用它完成C++语法上不允许的\
转换,在某些情况下程序员有需要的转换。例如,可以把某种引用或指针类型转换为其他引用类型或指针类型(两\
个类型可以不相关),这个关键字还经常将指针转换为void*,以及将void*转换为指针。
下面通过代码说明reinterpret_cast的使用:
#include <iostream>
using namespace std;
//测试int 和 void*的相互转化
void test_voidpointer(void *data){
int d = reinterpret_cast<int>(data);
cout << d << endl;
}
//定义连个无关类A, B
class A{
};
class B{
};
int _tmain(int argc, _TCHAR* argv[])
{
//void* 和in的相互转化,这里应该注意一下64位平台和32位平台指针的大小不同
test_voidpointer(reinterpret_cast<void *>(20));
//A a;
B b;
//a = reinterpret_cast<A>(b); //编译通不过,b不知指针或者引用
//下面是指针或引用的转化
A *pa = reinterpret_cast<A*>(&b);
A &ra = reinterpret_cast<A&>(b);
system("pause");
return 0;
}