dynamic_cast < type-id > ( expression )
If type-id is void*, a run-time check is made to determine the actual type of expression. The result is a pointer to the complete object pointed to by expression. For example:
// dynamic_cast_2.cpp // compile with: /c /GR 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 }
以上摘自Visual Studio 2015帮助文档.
多重继承时的转换如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class A
{
public:
int a;
virtual void fa(){}
};
class B
{
public:
int b;
virtual void fb(){}
};
class C :public A, public B //多重继承
{
public:
int c;
virtual void fc(){}
};
int main()
{
C* pc = new C();
A* pa = pc;
B* pb = pc;
//dynamic_cast转换void*
void* pva = dynamic_cast<void*>(pa);
void* pvb = dynamic_cast<void*>(pb);
//输出:a-b-c-pva-pvb: 02BF52A0 02BF52A8 02BF52A0 02BF52A0 02BF52A0
//后面三个值是一样的
printf("a-b-c-pva-pvb: %p %p %p %p %p\n", pa, pb, pc, pva, pvb);
return 0;
}