static_cast和dynamic_cast概述
动态类型转换dynamic_cast概述
dynamic_cast<type> (expr)
: dynamic_cast 在运行时执行转换,验证转换的有效性。如果转换未执行,则转换失败,表达式 expr 被判定为 null。dynamic_cast 执行动态转换时,type 必须是类的指针、类的引用或者 void*,如果 type 是类指针类型,那么 expr 也必须是一个指针,如果 type 是一个引用,那个 expr 也必须是一个引用。
静态类型转换static_cast概述
static_cast<type> (expr)
: static_cast 运算符执行非动态转换,没有运行时类检查来保证转换的安全性。例如,它可以用来把一个基类指针转换为派生类指针。
静态类型转换
//父子之间转换
class Base{};
class Child :public Base{};
class Other{};
void test02()
{
Base * base = NULL;
Child * child = NULL;
//把base转为 Child*类型 向下 不安全
Child * child2 = static_cast<Child*>(base);
//把child 转为 Base* 向上 安全
Base * base2 = static_cast<Base*>(child);
//转other类型 转换无效
//Other * other = static_cast<Other*>(base);
}
动态类型转换
基础类型不可以转换
void test03()
{
//基础类型不可以转换
char c = 'a';
//dynamic_cast非常严格,失去精度 或者不安全都不可以转换
double d = dynamic_cast<double>(c);
}
动态类型转换
如果发生了多态
class MyBase
{
virtual void func(){};
};
class MyChild :public MyBase
{
virtual void func(){};
};
class MyOther {};
void test05()
{
MyBase* base = NULL;
MyChild* child = NULL;
//child转Base * 向上 安全
MyBase* base = dynamic_cast<MyBase*>(child);
//base 转MyChild * 向下 不安全
//MyChild* child = dynamic_cast<MyChild*>(base);
//dynamic_cast 如果发生了多态,那么可以让基类转为派生类 ,向下转换
MyBase* base = new MyChild;
MyChild* child = dynamic_cast<MyChild*>(base);
}
总结
不可以转换基础数据类型
父子之间转换说明
父转子 不可以
子转父 可以
发生多态 都可以