为什么static_cast
不能从虚拟基地垂头丧气?
struct A {};
struct B : public virtual A {};
struct C : public virtual A {};
struct D : public B, public C {};
int main()
{
D d;
A& a = d;
D* p = static_cast<D*>(&a); //error
}
g++ 4.5 说:
error: cannot convert from base ‘A’ to derived type ‘D’ via virtual base ‘A’
解决方案是使用dynamic_cast
? 但为什么。什么是理性?
-- 编辑 --
下面很好的答案。没有答案详细说明子对象和 vtables 最终是如何被订购的。以下文章为 gcc 提供了一些很好的示例:
http ://www.phpcompiler.org/articles/virtualinheritance.html#Downcasting