• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

dynamic_castc++

原作者: [db:作者] 来自: [db:来源] 收藏 邀请


 

先看一下 别人总结的 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;
}

    

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#中使程序跳到指定行中发布时间:2022-07-14
下一篇:
c#正则表达式匹配回车发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap