C ++ - 向下转换没有RTTI / dynamic_cast的菱形继承对象 [英] C++ - downcasting a diamond shape inherited object without RTTI/dynamic_cast

查看:1020
本文介绍了C ++ - 向下转换没有RTTI / dynamic_cast的菱形继承对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在整合第三方套件,在非RTTI平台(Android)上使用大量的RTTI资料。基本上,我做了我自己的RTTI实现,但我遇到了一个问题。

I'm currently working on integrating a third-party package that uses lots of RTTI stuff on a non-RTTI platform (Android). Basically, I did my own RTTI implementation but I'm stuck on a problem.

问题是很多类都有钻石继承问题,因为所有的类派生自相同的基类(对象)..所以,如果我想从基类向下转换到派生类,我必须使用dynamic_cast - 但RTTI不可用!在没有dynamic_cast的情况下,如果有虚拟继承,我如何将对象从父对象转换为子对象?

The issue is that a lot of classes are having the diamond inheritance problem since all the classes derive from the same base class (object).. and so, if I want to downcast from the base class to the derived class, I have to use a dynamic_cast - but RTTI is not available! How do I convert an object from parent to child when there are virtual inheritance without dynamic_cast?

它看起来像这样:

class A 
{
public:
 virtual char* func() { return "A"; };
};
class B : public virtual A
{
public:
 //virtual char* func() { return "B"; };
};
class C : public virtual A 
{
public:
 //virtual char* func() { return "C"; };
};

class D : public B, public C 
{
public:
 //virtual char* func() { return "D"; };
};

D d;
A* pa = static_cast<A*>(&d);
D* pd = static_cast<D*>(pa); // can't do that! dynamic_cast does work though...

这是我的错误:


错误C2635:无法将'A *'转换为'D *';从虚拟基类的转换暗示

error C2635: cannot convert a 'A*' to a 'D*'; conversion from a virtual base class is implied

错误C2440:'initializing':无法从'test_convert :: A *'转换为'test_convert :: D *'
从基地到派生的投射需要dynamic_cast或static_cast

error C2440: 'initializing' : cannot convert from 'test_convert::A *' to 'test_convert::D *' Cast from base to derived requires dynamic_cast or static_cast

任何想法?

推荐答案

你只能使用 dynamic_cast 没有其他投射会做到这一点。

You can only do this cast with dynamic_cast; no other cast will do this.

如果你不能设计你的接口,所以你不需要执行这种类型的转换,那么你唯一可以做的是使你的类层次结构中的转换功能的一部分。

If you can't design your interfaces so that you don't need to perform this type of cast then the only thing you can do is make the casting functionality part of your class hierarchy.

例如(可怕的hacky)

E.g. (horribly hacky)

class D;

class A
{
public:
    virtual D* GetDPtr() { return 0; }
};

class B : public virtual A
{
};

class C : public virtual A 
{
};

class D : public B, public C 
{
public:
    virtual D* GetDPtr() { return this; }
};

这篇关于C ++ - 向下转换没有RTTI / dynamic_cast的菱形继承对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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