显式转换也被称为强制类型装欢,包括四个强制类型转换运算符:static_cast,dynameic_cast,const_cast和reinterpret_cast.使用强制类型转换就关闭了c++的类型检查设施,容易引起错误.但是有些情况下,我们需要强制类型转换.
Void*指针被称为通用指针,它可以指向任何类型的数据.但是void*zz不能解引用,因为没有类型信息.所以,void*的指针必须先转换为特定类型的指针.c++不允许从void*指针到其他类型指针的自动装欢,所以这是需要强制类型转换.
另外,我们有时希望通常的表转转换,或者避免出现多种转换可能的二义性情况,在这些情况下,都需要显式强制类型装欢.
限制装欢运算符的一般形式如下:
Castname<type>(expr);//将expr限制转换为type类型.
这里的castname是static_cast,dynamic_cast,const_cast,和reinterpret_cast之一.
Const_cast
将转换调表达式的常量性(一级volatile限定).列如:
Int main()
{
Const int I = 0;
Int *j = &I;//error
J = const_cast<int*>(&i);//pregerred
Volatile int k = 0;
Int* u = cost_cast<int*>(&i);
}
用const_cast执行一般的类型转换,或者用其他三种形式来转换掉常量都会引起编译错误.
const int consti = 0;
int*jj = const_cast<int *>(&consti);//OK
*jj = 10;//OK
Consti = 20;//Error
int*kj = static_cast<int *>(&consti);//Error
int*kkk = dynamic_cast<int *>(&consti);//Error
int*kkkk = reinterpret_cast<int *>(&consti);//Error
static_cast
可以显式进行编译器隐式进行的任何类型转换,”窄化”转换,具有潜在危险的类型转换,如void*指针的强制类型转换
算术值到枚举型的强制转换
基类到其派生类(或者指针或者引用)的强制转换.
如:
eunm mumble
{
First =1,
Second,
Thred
};
Extern int ival;
Mumble e = static_cast<mumble>(ival);//具有潜在的危险,因为正确性取决于ival的值
Reinterpret_cast
通常对于操作数的位模式执行一个比较低层次的重新解释,它的正确性很大程度上依赖于程序员的主动管理.
#inlcude<iostream.h>
Const int sz = 100;
Struct X
{
Int a[sz];
};
Void print(X* x)
{
For (int I = 0;i< sz;I ++)
{
//xxxx
}
}
Int main()
{
X x;
Print(&x);
Int* xp = reinterpret_cast<int*>(&x);
For (int*I = xp;I < xp+sz;I ++)
{
*I = 0;
}
Print(reinterpret_cast<X*>(xp));
}
Dynamic_cast
支持在运行时刻识别由指针或者引用指向的类对象.