C++中用dynamic_cast实现downcast之一见

本文讲述了在使用dynamic_cast进行向下转型时遇到的运行时错误,并详细记录了从困惑到最终解决问题的过程,强调了RTTI的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Almost   alway   it   will   be   on   the   right   track   if   we   use   "dynamic_cast "   for   up-casting,   with   either   a   pointer   or   a   reference,   to   a   type   of   sub-class   from   that   of   base-class,   and   this   would   be   guaranteed   to   be   safe   in   most   cases.   Nevertheless   possibly,   if   you   ever   deploy   it   by   yourself,   it   will   not   act   as   you   expect   if   you   use   this   casting   operator   for   down-casting   instead.   For   me,   not   so   that   lucky   it   is!

  Now   let 's   show   you   the   scenario   as   this:   Originally   I   dynamically   create   an   object   of   the   sub-class   and   assign   the   returned   pointer   to   a   pointer   to   the   base-class,   then   actually   I   just   intend   to   cast   this   pointer   to   base-class   back   to   pointer   to   the   sub-class,   which   seems   absolutely   reasonable   and   nothing   unpredictable   would   be   expected,   but   thing   only   to   run   out   of   its   normal   way!

  Passing   through   the   compilation   is   entirely   ok,   but   when   I   trigger   the   program,   an   run-time   error   bursts   out,   which   is   concerning   such   and   such   a   memory   allocation   on   the   heap.   Then   I   try   the   same   case   for   downcasting   a   reference   instead   of   pointer,   the   result   stands   the   same,   in   the   end   ,therefore,   I   am   buffled!

  After   nearly   a   week   of   being   bewildered   and   puzzled,   edificed   by   a   post   issued   from   a   fellow   CSDNer,   I   recall   a   critical   try   --   the   compilation   option   that   controls   the   support   for   RTTI.   Woo!   I   cry,   doesn 't   the   dynamic-cast   depend   on   the   sustenance   of   RTTI   by   the   run-time   system?  
   
  Definitely   that 's   the   key   I 've   been   dredging   toiling   to   search!   Immediately   after   I   open   the   option   in   the   compilation   configuration,   everything   goes   extremely   right! 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值