1 #include <iostream> 2 3 class A 4 { 5 public: 6 A(){} 7 ~A(){} 8 virtual int data(){return 1;} 9 }; 10 class B:public A 11 { 12 public: 13 B(){} 14 ~B(){} 15 int data(){return 2;} 16 }; 17 18 class C:public A 19 { 20 public: 21 C(){} 22 ~C(){} 23 int data(){return 3;} 24 }; 25 26 class D:public C 27 { 28 public: 29 D(){} 30 ~D(){} 31 int data(){return 4;} 32 }; 33 34 int main() 35 { 36 37 std::cout<<"dynamic_cast begin "; 38 A *a=new A; 39 B *b=new B; 40 C *c=new C; 41 D *d=new D; 42 43 if(dynamic_cast<B*> (a)) //this will fail 派生类不能指向基类 44 { 45 std::cout<<"A *a convert B class ok "; 46 } 47 48 if(dynamic_cast<A*> (b)) // this will be ok 基类指向派生类 ok 49 { 50 std::cout<<"B *b convert A class ok "; 51 } 52 53 54 if(dynamic_cast<C*> (a)) // 派生类不能指向基类 55 { 56 std::cout<<"A *a convert C class ok "; 57 } 58 59 if(dynamic_cast<A*> (c)) //c派生类 所以可以被A指向 60 { 61 std::cout<<"A *a convert C class ok "; 62 } 63 64 if(dynamic_cast<A*> (d)) // A <- C <- D 基类可以指向派生类 ok 65 { 66 std::cout<<"D *d convert A class ok "; 67 } 68 69 if(dynamic_cast<D*> (c)) // 派生类不能指向基类 70 { 71 std::cout<<"C *c convert D class ok "; 72 } 73 74 if(dynamic_cast<C*> (d)) // C基类可以指向派生类D ok 75 { 76 std::cout<<"D *d convert C class ok "; 77 } 78 79 if(dynamic_cast<D*> (d)) // ok 80 { 81 std::cout<<"d *d convert D class ok "; 82 } 83 84 std::cin.get(); 85 return 0; 86 }