Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1055722
  • 博文数量: 288
  • 博客积分: 10306
  • 博客等级: 上将
  • 技术积分: 3182
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-12 17:00
文章分类

全部博文(288)

文章存档

2011年(19)

2010年(38)

2009年(135)

2008年(96)

我的朋友

分类: C/C++

2010-01-25 14:13:36

关于dynamic_cast异常
2008-03-24 23:05

    前两天写了个程序,发生了异常,调试了半天发现是dynamic_cast,的异常

    class A{........}

    class B:public A{......}

int main()

{

     A *a = new B;

    B *p = dynamic_cast a //结果这里抛出了异常

}

找了半天的资料,理论是是可以的啊

MSDN上关于向下转型的解释: 
If the type of expression is a base class of the type of type-id, a run-time check is made to see if expression actually points to a complete object of the type of type-id. If this is true, the result is a pointer to a complete object of the type of type-id. For example: 

class B { ... }; 
class D : public B { ... }; 

void f() 

B* pb = new D; // unclear but ok 
B* pb2 = new B; 

D* pd = dynamic_cast(pb); // ok: pb actually points to a D 
... 
D* pd2 = dynamic_cast(pb2); // pb2 points to a B not a D 
// cast was bad so pd2 == NULL 
... 

This type of conversion is called a "downcast" because it moves a pointer down a class hierarchy, from a given class to a class derived from it.   
     最后发现原来vc6.0要支持向下转型要加入GR开关,而这在vc6.0z中是默认关闭的

基础很重要....哎

阅读(1458) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~