const A* pca = new A;
A* pa = const_cast<A*>(pca); //相当于A* pa = (A*)pca;
出于安全性考虑,const_cast无法将非指针的常量转换为普通变量。
static_cast
该函数主要用于基本类型之间和具有继承关系的类型之间的转换。
这种转换一般会更改变量的内部表示方式,因此,static_cast应用于指针类型转换没有太大意义。
例:
//基本类型转换
int i=0;
double d = static_cast<double>(i); //相当于 double d = (double)i;
//转换继承类的对象为基类对象
class Base{};
class Derived : public Base{};
Derived d;
Base b = static_cast<Base>(d); //相当于 Base b = (Base)d;
dynamic_cast
它与static_cast相对,是动态转换。
这种转换是在运行时进行转换分析的,并非在编译时进行,明显区别于上面三个类型转换操作。
该函数只能在继承类对象的指针之间或引用之间进行类型转换。进行转换时,会根据当前运行时类型信息,判断类型对象之间的转换是否合法。dynamic_cast的指针转换失败,可通过是否为null检测,引用转换失败则抛出一个bad_cast异常。
例:
class Base{};
class Derived : public Base{};
//派生类指针转换为基类指针
Derived *pd = new Derived;
Base *pb = dynamic_cast<Base*>(pd);
if (!pb)
cout << "类型转换失败" << endl;
//没有继承关系,但被转换类有虚函数
class A(virtual ~A();) //有虚函数
class B{}:
A* pa = new A;
B* pb = dynamic_cast<B*>(pa);
postfix-expression:
const_cast < type-id > ( expression )
The const_cast operator can be used to remove the const, volatile, and __unaligned attribute(s) from a class.
A pointer to any object type or a pointer to a data member can be explicitly converted to a type that is identical except for the const, volatile, and __unaligned qualifiers. For pointers and references, the result will refer to the original object. For pointers to data members, the result will refer to the same member as the original (uncast) pointer to data member. Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.
You cannot use the const_cast operator to directly override a constant variable's constant status.
The const_cast operator converts a null pointer value to the null pointer value of the destination type.