考虑这个简单的例子:
struct Base1 {};
struct Base2 {};
struct Derived : public Base1, public Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = static_cast<Base2*>(foo1);
}
我得到:
Error: static_cast from 'Base1 *' to 'Base2 *', which are not related by inheritance, is not allowed
编译器应该有足够的信息来确定Base2
可以在Derived
没有 RTTI ( dynamic_cast
) 的情况下获得这些信息并让我这样做:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
为什么不允许这样做?(有人可能会争辩说编译器不知道是否foo1
是Derived
类型,但即使从转换为例如static_cast
也不检查类型)Base1
Derived
注意:这个问题与我的类似,但并不完全相同,因为这里我们是交叉转换基类,而不是派生类