不能downcast因为类不是多态? [英] Can't downcast because class is not polymorphic?

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

问题描述

可以继承没有虚拟方法吗?编译器表示以下代码不是多态的。

Is it possible to have inheritance with no virtual methods? The compiler is saying that the following code is not polymorphic.

示例:

Class A(){
    int a;
    int getA(){return a;};
}


Class B(): A(){
    int b;
    int getB(){return b;};
}



在另一个类中,我们试图从 对象对象

In another class we are trying to downcast from an A object to a B object:

 A *a;
 B *b = dynamic_cast<B*>(a)

以下错误:

 cannot dynamic_cast ... (source type is polymorphic)


推荐答案

语法错误不能承受,你不能 dynamic_cast 非多态型。 static_cast 是在这种情况下使用的转换,如果你知道它实际上是目标类型的对象。

Syntax errors non-withstanding, you cannot dynamic_cast a non-polymorphic type. static_cast is the cast you would use in this case, if you know that it is in fact an object of the target type.

原因: static_cast 基本上让编译器在编译时执行检查输出?这可以用于您正在向上或向下继承指针(或引用)的继承层次结构的情况。但是检查只是在编译时,编译器假设你知道你在做什么。

The reason why: static_cast basically has the compiler perform a check at compile time "Could the input be cast to the output?" This is can be used for cases where you are casting up or down an inheritance hierarchy of pointers (or references). But the check is only at compile time, and the compiler assumes you know what you are doing.

dynamic_cast 只在指针或引用转换的情况下使用,并且除了编译时检查之外,它还执行额外的运行时检查转换是否合法。它要求所讨论的类至少有一个虚方法,这允许编译器(如果它支持RTTI)执行这个附加检查。但是,如果所讨论的类型没有任何虚拟方法,那么它不能使用。

dynamic_cast can only be used in the case of a pointer or reference cast, and in addition to the compile time check, it does an additional run time check that the cast is legal. It requires that the class in question have at least 1 virtual method, which allows the compiler (if it supports RTTI) to perform this additional check. However, if the type in question does not have any virtual methods, then it cannot be used.

最简单的情况,如果你传递指针这,是考虑使基类的析构函数虚拟化。除了允许你使用动态转换,它还允许在删除基类指针时调用适当的析构函数。

The simplest case, and probably worthwhile if you're passing pointers around like this, is to consider making the base class's destructor virtual. In addition to allowing you to use dynamic cast, it also allows the proper destructors to be called when a base class pointer is deleted.

这篇关于不能downcast因为类不是多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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