Converts the operand expression to an object of type type-id.
将操作数 expression 转换为类型type-id对象。
dynamic_cast < type-id > ( expression )
For example:
D* pd = new D;
C* pc = dynamic_cast<C*>(pd);
B* pb = dynamic_cast<B*>(pd);
主要应用于子类向父类的转换,而父类向子类转换则会产生异常,在bad_cast一文中有其对比
这种属于上行转换,如果type-id 是viod*类型,则靠后面的expression判断其类型
class A {virtual void f();};
class B {virtual void f();};
void f() {
A* pa = new A;
B* pb = new B;
void* pv = dynamic_cast<void*>(pa);
// pv now points to an object of type A
pv = dynamic_cast<void*>(pb);
// pv now points to an object of type B
}
如果 expression 的类型是 type-id类型的基类,则运行时检查进行查看 expression 是否指向实际 type-id的类型的完整对象。如果为 true,则结果是指向 type-id的类型的完整对象
#include <typeinfo.h>
#include <iostream>
using namespace std;
class B {
virtual void sum(int a,int b){}
};
class D : public B
{
virtual void sum(int a,int b){}
};
int main() {
B* pb = new D; // unclear but ok
B* pb2 = new B;
try {
D* pd = dynamic_cast<D*>(pb); // ok: pb actually points to a D
D* pd2 = dynamic_cast<D*>(pb2); // pb2 points to a B not a D
}catch (bad_cast b)
{
cout << "Caught: " << b.what();
}
return 0;
}