S.l.e!ep.¢%

像打了激速一样,以四倍的速度运转,开心的工作
简单、开放、平等的公司文化;尊重个性、自由与个人价值;
posts - 1098, comments - 335, trackbacks - 0, articles - 1
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

dynamic_cast,的异常

Posted on 2010-05-12 16:31 S.l.e!ep.¢% 阅读(558) 评论(0)  编辑 收藏 引用 所属分类: C++
前两天写了个程序,发生了异常,调试了半天发现是dynamic_cast,的异常

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

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

int main()

{

     A *a = new B;

    B *p = dynamic_cast<B*> 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<D*>(pb); // ok: pb actually points to a D
...
D* pd2 = dynamic_cast<D*>(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中是默认关闭的

基础很重要....哎


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理