为什么不能dynamic_cast“侧身”播放?在多重继承期间? [英] Why can't I dynamic_cast "sideways" 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.
是否可以使以上工作正常进行,还是需要添加
<? code>虚拟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.
这篇关于为什么不能dynamic_cast“侧身”播放?在多重继承期间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!