dynamics_cast<>

 #include <iostream>

 class A
{
public:
A(){}
~A(){}
virtual int data(){return ;}
};
class B:public A
{
public:
B(){}
~B(){}
int data(){return ;}
}; class C:public A
{
public:
C(){}
~C(){}
int data(){return ;}
}; class D:public C
{
public:
D(){}
~D(){}
int data(){return ;}
}; int main()
{ std::cout<<"dynamic_cast begin \n";
A *a=new A;
B *b=new B;
C *c=new C;
D *d=new D; if(dynamic_cast<B*> (a)) //this will fail 派生类不能指向基类
{
std::cout<<"A *a convert B class ok\n";
} if(dynamic_cast<A*> (b)) // this will be ok 基类指向派生类 ok
{
std::cout<<"B *b convert A class ok\n";
} if(dynamic_cast<C*> (a)) // 派生类不能指向基类
{
std::cout<<"A *a convert C class ok\n";
} if(dynamic_cast<A*> (c)) //c派生类 所以可以被A指向
{
std::cout<<"A *a convert C class ok\n";
} if(dynamic_cast<A*> (d)) // A <- C <- D 基类可以指向派生类 ok
{
std::cout<<"D *d convert A class ok\n";
} if(dynamic_cast<D*> (c)) // 派生类不能指向基类
{
std::cout<<"C *c convert D class ok\n";
} if(dynamic_cast<C*> (d)) // C基类可以指向派生类D ok
{
std::cout<<"D *d convert C class ok\n";
} if(dynamic_cast<D*> (d)) // ok
{
std::cout<<"d *d convert D class ok\n";
} std::cin.get();
return ;
}
上一篇:帝国cms栏目别名如何调用?


下一篇:为linux系统实现回收站