考虑以下简单示例:
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
可以在没有RTTI(Derived
)的情况下从dynamic_cast
到达,而我需要这样做:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
为什么不允许这样做? (有人可能会争辩说编译器不知道foo1
是否为Derived
类型,但是static_cast
仍然不检查类型,即使从Base1
转换为{例如{1}})
注意:这个question与我的类似,但并不完全相同,因为在这里我们是交叉转换基类,而不是派生基类
答案 0 :(得分:3)
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);
}
在使用合成(即界面)时,从Base1
到Base2
的这种转换是惯用的。