dynamic_cast是四个强制类型转换操作符之一
其余三个分别为:static_cast、const_cast、reinterpert_cast
在转换时,dynamic_cast会检查转换的source对象是否真的可以转换成target类型,这种检查不是语法上的,而是真实情况的检查。
dynamic_cast主要用于“安全地向下转型”
dynamic_cast用于类继承层次间的指针或引用转换。主要还是用于执行安全的向下转型(safe downcasting),也即是基类对象的指针或引用转换为同一继承层次的其他指针或引用。至于“先上转型”(即派生类指针或引用类型转换为其基类类型),本身就是安全的,无需转换。
class Base
{
public:
Base(){};
virtual void Show(){cout<<"This is Base calss";}
};
class Derived:public Base
{
public:
Derived(){};
void Show(){cout<<"This is Derived class";}
};
int main()
{
Base *base ;
Derived *der = new Derived;
//base = dynamic_cast<Base*>(der); //正确,但不必要。
base = der; //先上转换总是安全的
base->Show();
system("pause");
}
dynamic_cast向下转型的种类
一种是基类指针所指对象是派生类类型的,这种转换是安全的;
另一种是基类指针所指对象为基类类型,在这种情况下dynamic_cast在运行时做检查,转换失败,返回结果为0;
#include "stdafx.h"
#include<iostream>
using namespace std;
class Base
{
public:
Base(){};
virtual void Show(){cout<<"This is Base calss";}
};
class Derived:public Base
{
public:
Derived(){};
void Show(){cout<<"This is Derived class";}
};
int main()
{
//这是第一种情况
Base* base = new Derived;
if(Derived *der= dynamic_cast<Derived*>(base))
{
cout<<"第一种情况转换成功"<<endl;
der->Show();
cout<<endl;
}
//这是第二种情况
Base * base1 = new Base;
if(Derived *der1 = dynamic_cast<Derived*>(base1))
{
cout<<"第二种情况转换成功"<<endl;
der1->Show();
}
else
{
cout<<"第二种情况转换失败"<<endl;
}
delete(base);
delete(base1);
system("pause");
}
运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/aed926a5a36f4230a025a4d476692922.jpeg)
类型转换和对象引用语句合并的注意事项
一般来说,为了避免创造无用的新变量(主要是懒得想名字),会选择进行语句合并,对于基类中重复出现的变量,直接转换会报错变量不明确,例如:
class Base0
{
public:
Base0(){};
virtual void Show(){cout<<"This is Base0 calss";}
int health = 0;
};
class Base1: public Base0
{
public:
Base1(){};
virtual void Show(){cout<<"This is Base1 calss";}
int health = 1;
};
class Derived:public Base1
{
public:
Derived(){};
void Show(){cout<<"This is Derived class";}
};
int main()
{
Base *base ;
Derived *der = new Derived;
Base1* base1 = der
int BaseHealth_0 = base1->health //正确,先直接向上转换,再进行对象引用
int BaseHealth_1 = dynamic_cast<Base1*>(der)->health //正确,使用了dynamic_cast进行类型转换
int BaseHealth_2 = der->health //错误,会报错变量不明确,原因在于Base0、Base1均
有health
system("pause");
}