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

以下代码抛出 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.

相关文章