为什么我不能动态投射“横向"?在多重继承期间?

Why can#39;t I dynamic_cast quot;sidewaysquot; during multiple inheritence?(为什么我不能动态投射“横向?在多重继承期间?)

本文介绍了为什么我不能动态投射“横向"?在多重继承期间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码抛出 std::bad_cast

The following code throws std::bad_cast

struct Foo {
    void foo () {}
};

struct Bar {
    Bar () {
        dynamic_cast <Foo &> (*this) .foo ();
    }
    virtual ~ Bar () {}
};

struct Baz : public Foo, public Bar {
};

int main ()
{
    Baz b;
}

我记得曾经读过 dynamic_cast 如何权衡实现性能,因为它遍历完整的继承格"以便正确评估.这里编译器要做的就是先上投再下投.

I remember once reading how dynamic_cast has implementation performance trade-offs because "it traverses the full inheritence lattice" in order to evaluate correctly. What the compiler needs to do here is first cast up and then down again.

是否有可能使上述工作或我需要添加虚拟Foo* Bar::as_foo()=0;?

Is it possible to make the above work or do I need to add virtual Foo* Bar::as_foo()=0; ?

推荐答案

Foo 中没有虚函数,因此 dynamic_cast 完全不得不失败.需要有一个虚函数.在施工期间这样做也是一个坏主意,因为您会遇到施工订单问题.

There are no virtual functions in Foo, so dynamic_cast is perfectly obliged to fail. There needs to be a virtual function. It's also a bad idea to do so during construction, as you're going to run into construction order issues.

这篇关于为什么我不能动态投射“横向"?在多重继承期间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么我不能动态投射“横向"?在多重继承期间?

基础教程推荐