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

Why is this cross-cast not allowed?

本文关键字:广播 不允许 为什么      更新时间:2023-10-16

考虑这个简单的例子:

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 (dynamic_cast( 的情况下从Derived访问,并让我做:

Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;

为什么不允许这样做?(有人可能会争辩说,编译器不知道foo1是否属于Derived类型,但static_cast即使在从Base1转换为Derived时也不会检查该类型(

注意:这个问题与我的类似,但并不完全相同,因为这里我们是交叉转换基类,而不是派生的

static_cast会失败,因为非正式地说,Base1Base2是不相关的。

但是,如果您的类是多态的,则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的转换在使用组合(即接口(时是惯用的。