dynamic_cast是C++四个强制类型转换操作符中最特殊的一个,它支持运行时识别指针或引用。
dynamic_cast 用于类继承层次间的指针或引用转换。主要还是用于执行“安全的向下转型(safe downcasting)”,也即是基类对象的指针或引用转换为同一继承层次的其他指针或引用。
至于“向上转型”(即派生类指针或引用类型转换为其基类类型),本身就是安全的,尽管可以使用dynamic_cast进行转换,但这是没必要的, 普通的转换已经可以达到目的。
“向下转型”的前提条件:被转换对象必须是多态类型(必须公有继承自其他类,或者有虚函数)。
下面的代码就是向上转型:
#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 ;
Derived *der = new Derived;
//base = dynamic_cast<Base*>(der); //正确,但不必要。
base = der; //先上转换总是安全的
base->Show();
}
“向下转型”有两种情况。
- 一种是基类指针所指对象是派生类类型的,这种转换是安全的;
- 另一种是基类指针所指对象为基类类型,在这种情况下dynamic_cast在运行时做检查,转换失败,返回结果为0;
#include <iostream>
using namespace std;
class Base
{
public:
Base(){};
virtual void Show(){cout<<"This is Base calss" << endl;}
};
class Derived:public Base
{
public:
Derived(){};
void Show(){cout<<"This is Derived class" << endl;}
void d_f()
{cout << "d_f" << endl;}
};
class Derived1:public Base
{
public:
Derived1(){};
void Show(){cout<<"This is Derived1 class" << endl;}
void d_f()
{cout << "d1_f" << endl;}
};
void f(Base *p)
{
Derived *d;
if (d = dynamic_cast<Derived *>(p))
{
d->d_f();
d->Show();
}
}
int main()
{
Derived d1;
Derived1 d2;
f(&d2);
Base *p = new Derived;
f(p);
Base *p1 = new Base;
f(p1);
#if 0
Derived d;
Base *p = new Derived;
//Derived *pd = static_cast<Derived *>(p);
Derived *pd = dynamic_cast<Derived *>(p);
pd->Show(); //派生类中的函数
Base *p1 = new Base;
//pd = dynamic_cast<Derived *>(p1); //运行返回值为0
pd = static_cast<Derived *>(p1);
pd->Show(); //基类中的函数
pd->d_f();
#endif
}