动态转换不为非多态基类工作?

编程入门 行业动态 更新时间:2024-10-11 21:22:27
本文介绍了动态转换不为非多态基类工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这里,第二个转换错误说明

Here the second cast gives an error saying

cast.cc:35:35:error:can not dynamic_cast'base' 'class CBase *')to type'class CDerived *'(source type is not polymorphic)

CBase * base = new CDerived; CBase* pb; CDerived * der = new CDerived; CDerived* pd; pb = dynamic_cast<CBase*>(der); // ok: derived-to-base pd = dynamic_cast<CDerived*>(base); // wrong: base-to-derived

这个是什么意思

为什么这么做如果我使基类多态?

And why this works if I make the base class polymorphic ?

有人可以让我知道这背后的基本概念。

Can some one please let me know the basic concept behind this.

推荐答案

因为标准说的是这样(见C ++标准中的[expr.dynamic.cast]部分):

Because the standard says so (see the section [expr.dynamic.cast] in the C++ standard):

... dynamic_cast< T>(v)

... v 应为多态类型的指针或值。

... v shall be a pointer to or an lvalue of a polymorphic type

在实践中,由于运行时类型信息(RTTI)需要进行动态展开(即从基本到派生)可能与 vtbl / vptr机制一起生成,如果没有多态成员函数,则不需要。

In practice, because the run-time type information (RTTI) required to make dynamic down-casts (i.e. from base to derived) possible are generated along with the vtbl/vptr mechanism, which isn't required if there are no polymorphic member functions.

另一方面,向上扩展(即派生为base) RTTI(没有运行时决定做)。引用标准的同一部分:

Up-casts (i.e. derived to base), on the other hand, require no RTTI (there's no run-time decision to be made). Quoting from the same section of the standard:

struct B { }; struct D : B { }; void foo(D* dp) { B* bp = dynamic_cast<B*>(dp); // equivalent to B* bp = dp; }

更多推荐

动态转换不为非多态基类工作?

本文发布于:2023-08-04 03:17:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不为   多态   动态   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!