C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
static_cast 静态类型转换。如int转换成char
reinterpreter_cast 重新解释类型
dynamic_cast 命名上理解是动态类型转换。如子类和父类之间的多态类型转换。
const_cast, 字面上理解就是去除const属性。
4种类型转换的格式:
TYPE B = static_cast (a)
static_cast
int num1 = (int)dpi; //C类型转换
int num2 = static_cast<int>(dpi); //静态类型转换 编译的时c++编译器会做类型检查
int num3 = dpi; //c语言中 隐式类型转换的地方 均可使用 static_cast<>() 进行类型转换
reinterpreter_cast
//char* ===> int *
char *p1 = "hello...itcast ";
int *p2 = NULL;
//p2 = static_cast<int*>(p1); // 使用static_cast, 编译器编译时,会做类型检查 若有错误 提示错误
p2 = reinterpret_cast<int *>(p1); //若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释
cout << "p1:" << p1 << endl; //%s
cout <<"p2" << p2 << endl; //%d
dynamic_cast
void playObj(Animal *base)
{
base->cry(); // 1有继承 2虚函数重写 3 父类指针 指向子类对象 ==>多态
//能识别子类对象
// dynamic_cast 运行时类型识别 RIIT
Dog *pDog = dynamic_cast<Dog *>(base);
if (pDog != NULL)
{
pDog->doHome(); //让够 做自己 特有的工作
}
Cat *pCat = dynamic_cast<Cat *>(base); //父类对象 ===> 子类对象
//向下转型
//把老子 转成 小子
if (pCat != NULL)
{
pCat->doThing(); //让够 做自己 特有的工作
}
}
const_cast,
//const char * ===> char * //把只读属性 去掉
p1 = const_cast<char *>(p);