动态转换不为非多态基类工作? [英] dynamic cast not working for non polymorphic base class?

查看:125
本文介绍了动态转换不为非多态基类工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}


这篇关于动态转换不为非多态基类工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆