1.reinterprent_cast的基本用法
reinterprent_cast是最不安全的类型转换,主要用在不同类型的指针,引用,和与指针赋值兼容的整形之间的转换,一般很少用,可以理解为重解析内存,reinterprent_cast转换时,是逐bit进行转换的。
````c++
#include <iostream>
class Parent {
public:
explicit Parent() {
std::cout << "Parent 构造函数" << std::endl;
}
~Parent() {
std::cout << "Parent 析构函数" << std::endl;
}
public:
int pData = 15;
};
class Son :public Parent {
public:
using Parent::Parent;
~Son() {
std::cout << "Son的析构函数" << std::endl;
}
public:
int sData = 20;
};
int main() {
/ int转为char* ****/
int iValue = 10;
int pValue = &iValue;
//实际上解析出来的是10,但是访问时会报异常,内存访问出错
char p = reinterpret_cast<char>(iValue);
//std::cout << p << std::endl;
//p = 20; //给p地址处写入20,但是p的地址本身不可访问
p = new char('a');
p = 'A';
std::cout << *p << std::endl;
/**/
/*************************char * 转为int * ********************/
char pchar = 'B';
char* q = &pchar;
int* pInt_c;
pInt_c = reinterpret_cast<int*>(q); //可以转换成功,且值可以访问,但是值是错的
std::cout << *pInt_c << std::endl;
/**************************************************************/
/***********************父类对象转为子类*******************************/
Parent *par = new Parent;
Son *sn = new Son;
//s = reinterpret_cast<Parent*>(s); //不能执行转换
//p = reinterpret_cast<Son*>(s); //不能执行转换
/**********************************************************************/
/*****************************************int转为地址**************************/
int reg = 0x12526584;
int* rValue;
rValue = reinterpret_cast<int*>(reg); //可以,表示rValue的指向的内存单元的编号是0x12526584
//int* address = static_cast<int*>(reg); //不可以
int* addressAnother = (int*)(reg); //c类型的强制类型转换。可以,表示rValue的指向的内存单元的编号是0x12526584
std::cout << "rValue is " << *rValue << std::endl; //异常,试图访问一个不是正规申请来的内存单元
/*******************************************************************************/
system("pause");
return 0;
}
> -\ []**reinterprent_cast最好不要使用,容易引起特别多的问题,如果必须要使用,需要做好异常捕获处理机制**