1.reinterpret_cast
/************************************************************************/
/* 4种显示转换的使用方法,含义,使用注意事项: */
/************************************************************************/
#include<iostream>
using namespace std;
int main()
{
/*
1.reinterpret_cast
将一个类型的指针,转换为另一个类型的指针。这种转换不用修改指针变量值数据存放格式(不改变指针变量值)
只需要在编译时重新解指针的类型就可做到;
*/
double d = 9.3;
double *pd = &d;
int sized = sizeof(double);
int sizei = sizeof(int);
cout<<sized<<endl;
cout<<sizei<<endl;
int *pi = reinterpret_cast<int *>(pd);
cout<<"value before changed:"<<pd<<endl;//L1
cout<<"value = "<<d<<endl;
cout<<"value after changed:"<<pi<<endl;//L2
cout<<"value = "<<*pi<<endl;
return 0;
}
从中L1/L2中可以看到指针变量的值并没有改变。
不能将reinterpret_cast 用于以下几种情况:
1)非指针类型的转换
2)contst指针 转换为void* 指针
2.const_cast
/*
2.const_cast 用于除去指针变量的常量属性,将它转换为一个对应指针类型的普通变量。
*/
int value1 = 0;
const int *pci = 0;
int *pj = const_cast<int *>(pci);//L1相当于int *pj = (int *)pci;
pj = &value1;
pci = &value1;
*pj = 10;
//*pci = 20; //报错error C2166: l-value specifies const object
其中不能够将L1语句替换为:
int *pj = pci;
其中可以将非const指针变量转换为 const 指针变量:
int *i = 0;
int const *_i = const_cast<const int *>(i);
因为cont int *不能够转换为int *。
不能够将const_cast用于以下情况:
1)无法将非指针的常变量转换为普通变量。
3.static_cast
/*
3.static_cast 主要用于基本类型之间和具有继承关系的类型之间的转换,这种转换一般会更改变量的内部表示方式,
因此static_cast应用于指针类型转换,没有太大意义,即使允许指针类型转换,也不及reinterpret_cast解释效率高。
*/
//1)基本类型转换
int i = 0;
double d = static_cast<double>(i);
int j = static_cast<int>(d);
//2)转换继承类型的对象为基类对象。
class Base{};
class Derived:public Base{};
Derived d1;
Base b1 = static_cast<Base>(d1);
4.dynamic_cast
/*
4.与静态static_const 相对,是动态dynamic_cast转换。
这种转换是在运行时,进行转换的,并非在编译时进行,明显区别于上面3个类型转换操作。
其只能在继承对象的指针之间或引用进行类型转换。
*/
//继承,指针
class Base{};
class Derived:public Base{};
Derived *pd = new Derived;
Base *pb = dynamic_cast<Base *>(pd);
if (!pb)
{
cout<<"change success"<<endl;
}
else
{
cout<<"change failed"<<endl;
}
//继承,引用
Derived d;
Base &b = dynamic_cast<Base &>(d);
//没有继承关系,但是被转换的类有虚函数
class A{virtual ~A(){}};
class B{};
A* pa1 = new A;
B* pb1 = dynamic_cast<B*>(pa1);
if (!pb)
{
cout<<"dynamic_cast success"<<endl;
}
else
{
cout<<"dynamic_cast failed"<<endl;
}