以下代码抛出 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 如何权衡实现性能,因为“它遍历完整的继承格”以便正确评估。编译器在这里需要做的是先向上投射,然后再向下投射。
是否可以使上述工作或我需要添加
virtual Foo* Bar::as_foo()=0;
?