多继承从基类转换到不同的派生类 [英] Multiple inheritance casting from base class to different derived class

查看:102
本文介绍了多继承从基类转换到不同的派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设有这样的类层次结构:

Let's assume there is such class hierarchy:

class A //base class

class B //interface

class C : public A, public B

创建C对象:

A *object = new C();

是否可以将对象传递给B?

Is it possible to cast object to B ?

重要:我假设我不知道对象是C.我只知道它实现了接口B

Important: I assume I don't know that object is C. I just know that it implements interface B

推荐答案

。这是不可能的(直接从 A * B * )。

No. This is not possible (direct casting from A* to B*).

因为 A B 的地址位于类C 。因此,投射会始终不安全,并且可能会出现意外行为演示

Because the address of A and B are at different locations in class C. So the cast will be always unsafe and possibly you might land up in unexpected behavior. Demo.

投射应始终通过 class C 。例如

A* pa = new C();
B* pb = static_cast<C*>(pa);
                   ^^^^ go through class C

Demo

这篇关于多继承从基类转换到不同的派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆