reinterpret_cast
等价于C语言中的类型转换
int main(){
int n = 1;
int* p = n;
}
按道理, 应该无法转换
然后强制转换, 解决问题
int main(){
// 显式强转
int n = 1;
int* p = (int*)n;
}
C++为了统一, 也还是创建了一个转换方式, 来替换强转
跟显示的强转, 没有任何区别, 只是看起来更加的清晰而已, 可读性更好
用于高风险的转换方式
整形转指针
各种类型的指针转换
父类, 子类指针的转换
int main(){
// 显式强转
int n = 1;
// 整形转指针
int* p = reinterpret_cast<int*>(n);
// 各种类型的指针转换 int*->char*
char* pCh = reinterpret_cast<char*>(p);
// 父类, 子类指针的转换
}
以下编译通过, 很显然, 这种转换方式, 不存在检查
汇编图
#include <iostream>
using namespace std;
class CFather{
};
class CSon: public CFather{
};
int main(){
CSon* pSon;
CFather* pFather;
pSon = reinterpret_cast<CSon*>(pFather);
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void foo(){
cout << "foo()" << endl;
}
int main() {
int nTemp = 0;
// 指针转整数
int nTemp1 = reinterpret_cast<int>(&nTemp);
cout << hex << nTemp1 << '\n';
//整数转指针
int* p1 = reinterpret_cast<int*>(nTemp1);
cout << *p1 << '\n';
//将整型转为指针
unsigned int nTemp2 = 0x00500000;
int* pTemp = reinterpret_cast<int*>(nTemp2);
//将一个函数转为一个函数指针并转回
void(*fp1)() = reinterpret_cast<void(*)()>(foo);
int(*fp2)() = reinterpret_cast<int(*)()>(fp1);
cout << dec << fp2() << '\n';
}