考虑这个简单的例子:
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
编译器应该有足够的信息来确定可以在没有RTTI(Base2
)的情况下从Derived
到达dynamic_cast
:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
为什么不允许这样做? (有人可能会争辩说编译器不知道foo1
是否为Derived
类型,但即使static_cast
也不会检查类型,即使例如从Base1
转换为Derived
时也是如此)
注:此question与我的相似,但并不完全相同,因为这里我们是交叉转换基类,而不是派生基类
A static_cast
将失败,因为非正式地说,Base1
和Base2
不相关。
但是如果您的类是polymorphic,dynamic_cast
将起作用:您可以通过添加虚拟析构函数来实现:
struct Base1 {virtual ~Base1() = default;};
struct Base2 {virtual ~Base2() = default;};
struct Derived : Base1, Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = dynamic_cast<Base2*>(foo1);
}
[