为什么不允许这种交叉广播?

时间:2020-01-06 07:46:40

标签: c++ static-cast cross-cast

考虑以下简单示例:

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与我的类似,但并不完全相同,因为在这里我们是交叉转换基类,而不是派生基类

1 个答案:

答案 0 :(得分:3)

static_cast将失败,因为从非正式角度来说,Base1Base2无关。

但是,如果您的类是 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); 
}

在使用合成(即界面)时,从Base1Base2的这种转换是惯用的。