为什么不允许这种跨性别演员选择?

huangapple go评论78阅读模式
英文:

Why is this cross-cast not allowed?

问题

我得到以下错误消息:

错误: 无法使用 static_cast 从 'Base1 *' 转换到 'Base2 *',它们之间没有继承关系

编译器应该有足够的信息来确定可以从 Derived 到达 Base2,而不需要使用 RTTI(dynamic_cast),并让我这样做:

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

为什么不允许这样做呢?(可以争论编译器不知道 foo1 是否为 Derived 类型,但即使从例如 Base1 转换到 Derived 时,static_cast 也不会检查类型。)

英文:

Consider this simple example:

struct Base1 {};

struct Base2 {};

struct Derived : public Base1, public Base2 {};

int main()
{
   Derived foo;
   Base1* foo1 = &amp;foo;
   Base2* foo2 =  static_cast&lt;Base2*&gt;(foo1); 
}

I get:

Error: static_cast from &#39;Base1 *&#39; to &#39;Base2 *&#39;, which are not related by inheritance, is not allowed

The compiler should have enough information to figure out that Base2 can be reached from Derived without RTTI (dynamic_cast) and having me to do:

Derived* foo3 = static_cast&lt;Derived*&gt;(foo1);
Base2* foo2 = foo3;

Why isn't this allowed? (One could argue that the compiler doesn't know if foo1 is of Derived type, but static_cast doesn't check the type anyway even when converting from Base1 to Derived for example)

Note: This question is similiar to mine, but it's not quite the same because here we are cross-casting base classes, not derived ones

答案1

得分: 3

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 的这种转型是惯用的。

英文:

A static_cast will fail since, informally speaking, Base1 and Base2 are not related.

However a dynamic_cast will work if your classes are polymorphic: which you can achieve by adding virtual destructors:

struct Base1 {virtual ~Base1() = default;};

struct Base2 {virtual ~Base2() = default;};

struct Derived : Base1, Base2 {};

int main()
{
   Derived foo;
   Base1* foo1 = &amp;foo;
   Base2* foo2 =  dynamic_cast&lt;Base2*&gt;(foo1); 
}

This casting from Base1 to Base2 is idiomatic when working with composition (i.e. interfaces).

huangapple
  • 本文由 发表于 2020年1月6日 15:46:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定