dynamic_cast c++


 

先看一下 别人总结的 c++ 四大 转换

static_cast 、 dynamic_cast 、const_cast、reinterpret_cast

http://www.jellythink.com/archives/205

 

要补充的是

1.dynamic_cast  在进行 下行转换时 父类 必须含有 虚函数(本质是 必须含有 虚函数表) 

上行转换没有问题 (不管有没有虚函数),无论是 指针还是引用,都会有这个限制

这种特性 上面的链接里面 有提到 但是只是说了 在进行 void*转换时需要 虚函数,不全面;

见下面代码

 

 1 class Parent {
 2 
 3 public :
 4      void foo() {
 5     
 6         cout << "this is Parent 's foo function " << endl;
 7     }
 8 
 9 };
10 class ChildA :public Parent {
11 
12 
13 
14 };
15 
16 class ChildB :public Parent {
17 
18 
19 
20 };
21 
22 typedef  void(*Fun)(void);
23 
24 int main(int argc,char** agr)
25 {
26     Parent * pp = new Parent();
27 
28     ChildA* pa = dynamic_cast<ChildA*>(pp);
29   
    /*Parent pp;
     Parent& pRea = pp;
     ChildA& pa = dynamic_cast<ChildA&>(pRea);
*/
//报同样的错
30 return 0; 31 }


上面因为 基类Parent  里面没有 虚函数  所以 在 28 行 直接报错 ,编译都不行

 错误为: 运行时dynamic_cast 的操作数 必须包含多态类类型;

 

2.dynamic_cast可以引用类型的 转换,但是对于下行转换 ,编译时不报错,运行时报错

见下面代码,(包含了 相同基类,跨类转换)

 1 // Test.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 using namespace std;
 7 class Parent {
 8 
 9 public :
10     virtual void foo() {
11     
12         cout << "this is Parent 's foo function " << endl;
13     }
14 
15 };
16 
17 
18 class ChildA :public Parent {
19 
20 
21 
22 };
23 
24 class ChildB :public Parent {
25 
26 
27 
28 };
29 
30 typedef  void(*Fun)(void);
31 
32 int main(int argc,char** agr)
33 {
34     Parent pp;
35     Parent& pRea = pp;
36     ChildA& pa = dynamic_cast<ChildA&>(pRea);
37     /*
38         ChildB pp;
39     ChildB& pRea = pp;
40     ChildA& pa = dynamic_cast<ChildA&>(pRea);
41     */
42     
43 
44 
45 
46     return 0;
47 }

报错是:std::bad_cast ,运行时报错

但是 其中对于 相同基类的跨类转换

指针是不报错的,只是得到的是空

// Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
class Parent {

public :
    virtual void foo() {
    
        cout << "this is Parent 's foo function " << endl;
    }

};


class ChildA :public Parent {



};

class ChildB :public Parent {



};

typedef  void(*Fun)(void);

int main(int argc,char** agr)
{
    ChildB* pp =  new ChildB;
    
    ChildA* pa = dynamic_cast<ChildA*>(pp);
     /// 这里的pa 是NULL而已 但不会报错   
    return 0;
}

    

 

posted @ 2017-09-08 10:09  CodeWu  阅读(480)  评论(0编辑  收藏  举报