/******************************************************************** file name : CLK.h author : Clark/陈泽丹 created : 2011-12-12 purpose : 测试dynamic_cast的转换有效性 测试结果发现dynamic_cast的只能在 [根结点, 实例化对象所处的类] 的路径上才能成功转换 *********************************************************************/ #include <iostream> using namespace std; #define DECLARE_CLASS_CREATE(class_name) static char* getName() { return #class_name; }; template<class T_TYPE> class T2T { public: typedef T_TYPE CUR_TYPE; }; class Root { public: DECLARE_CLASS_CREATE(Root) virtual void show(){} }; class Root_1Ex:public Root { public: DECLARE_CLASS_CREATE(Root_1Ex) }; class Root_1Ex_1Ex:public Root_1Ex { public: DECLARE_CLASS_CREATE(Root_1Ex_1Ex) }; class Root_2Ex:public Root { public: DECLARE_CLASS_CREATE(Root_2Ex) }; template<class T_Base, class T_Ex, class T_Test> void Test_Dynamic_Cast(T_Base obj1, T_Ex obj2, T_Test obj3) { cout<<"-----------------------------------------------------------"<<endl; T_Base::CUR_TYPE* pBase = new T_Ex::CUR_TYPE(); if( NULL != pBase) { cout<<"Succeed: "<<T_Base::CUR_TYPE::getName()<<" = new "<< T_Ex::CUR_TYPE::getName()<<endl; } else { cout<<"Failed: "<<T_Base::CUR_TYPE::getName()<<" = new "<< T_Ex::CUR_TYPE::getName()<<endl; } T_Test::CUR_TYPE* pTest = dynamic_cast<T_Test::CUR_TYPE*>(pBase); if( NULL != pTest) { cout<<"Succeed: "<<"dynamic_cast<"<< T_Test::CUR_TYPE::getName()<<"*>("<<T_Base::CUR_TYPE::getName()<<")"<<endl; } else { cout<<"Failed: "<<"dynamic_cast<"<< T_Test::CUR_TYPE::getName()<<"*>("<<T_Base::CUR_TYPE::getName()<<")"<<endl; } cout<<"-----------------------------------------------------------"<<endl; cout<<endl; } void main() { Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex>(), T2T<Root_1Ex>()); Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex>(), T2T<Root_1Ex_1Ex>()); Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex>(), T2T<Root_2Ex>()); Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex_1Ex>(), T2T<Root_1Ex>()); system("pause"); }
运行结果:
-----------------------------------------------------------
Succeed: Root = new Root_1Ex
Succeed: dynamic_cast<Root_1Ex*>(Root)
-----------------------------------------------------------
-----------------------------------------------------------
Succeed: Root = new Root_1Ex
Failed: dynamic_cast<Root_1Ex_1Ex*>(Root)
-----------------------------------------------------------
-----------------------------------------------------------
Succeed: Root = new Root_1Ex
Failed: dynamic_cast<Root_2Ex*>(Root)
-----------------------------------------------------------
-----------------------------------------------------------
Succeed: Root = new Root_1Ex_1Ex
Succeed: dynamic_cast<Root_1Ex*>(Root)
-----------------------------------------------------------