为什么不允许这种跨播?

问题描述 投票:0回答:1

考虑这个简单的例子:

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

c++ static-cast cross-cast
1个回答
3
投票

A static_cast将失败,因为非正式地说,Base1Base2不相关。

但是如果您的类是polymorphicdynamic_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的这种转换在使用composition(即接口)时是惯用的。

© www.soinside.com 2019 - 2024. All rights reserved.