dynamic_cast与static_cast使用

dynamic_cast与static_cast用于子类与基类之间的转换。

首先dynamic_cast:

 1 #include <iostream>
 2 using namespace std;
 3 class A{
 4     public:
 5         virtual ~A(){} //使用dynamic_cast时,必要!
 6 };
 7 class B:public A{
 8     public:
 9         B(){
10             m_b=12;
11         }
12         void foo(){
13             cout<<"B: "<<m_b<<endl;
14         }
15     private:
16         int m_b;
17 };
18 int main()
19 {    
20     A *a=new B();
21     B *b=dynamic_cast<B*>(a);
22     b->foo();
23     delete a;
24     return 0;
25 }

上面没有virtual ~A(){},编译时会报错:(source type is not polymorphic)。

static_cast:

 1 #include <iostream>
 2 using namespace std;
 3 class A{
 4     public:
 5         A():m_a(32){}
 6         void foo(){
 7             cout<<"A: "<<m_a<<endl;
 8         }
 9         void setA(int a){
10             m_a=a;
11         }
12     private:
13         int m_a;
14 };
15 class B:public A{
16     public:
17         B(){
18             m_b=12;
19             setA(13);
20         }
21         void foo(){
22             cout<<"B: "<<m_b<<endl;
23         }
24     private:
25         int m_b;
26 };
27 int main()
28 {    
29     A *a=new B();
30     B *b=static_cast<B*>(a);
31     A *aa=static_cast<A*>(b);
32     b->foo();
33     aa->foo();
34     delete a;
35     return 0;
36 }

打印a、b、aa地址,可知地址一样。

posted @ 2013-10-19 18:54  除e尘  阅读(284)  评论(0编辑  收藏  举报