为什么不允许跨播?

问题描述 投票: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个回答
0
投票

如果您的示例确实可以编译,那么它也应该已经编译:

struct Base1 {};

struct Base2 {};

Base1* blackBox();

int main()
{
   Base1* foo1 = blackBox();
   Base2* foo2 =  static_cast<Base2*>(foo1); 
}

将类的指针转换为完全不相关的类的指针是什么意思?该指针是指向Base1对象还是从Base1Base2派生的另一个对象?没有办法知道。请记住,C ++是一种静态类型的语言,必须在编译时知道语法上有效的语言,以便可以生成明智的机器代码。

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