c++ - 无法转换具有多重继承的类

标签 c++ casting multiple-inheritance virtual-inheritance

我正在尝试重构一些代码,同时保留现有功能。我无法将指向对象的指针强制转换为基接口(interface),然后稍后再获取派生类。在某些情况下,该程序使用工厂对象来创建这些对象的实例。

以下是我正在使用的类的一些示例。

// This is the one I'm working with now that is causing all the trouble.
// Some, but not all methods in NewAbstract and OldAbstract overlap, so I
// used virtual inheritance.
class MyObject : virtual public NewAbstract, virtual public OldAbstract { ... }

// This is what it looked like before
class MyObject : public OldAbstract { ... }

// This is an example of most other classes that use the base interface
class NormalObject : public ISerializable

// The two abstract classes. They inherit from the same object.
class NewAbstract : public ISerializable { ... }
class OldAbstract : public ISerializable { ... }

// A factory object used to create instances of ISerializable objects.
template<class T> class Factory
{
public:
    ...
    virtual ISerializable* createObject() const
    {
        return static_cast<ISerializable*>(new T()); // current factory code
    }
    ...
}

This question有关于不同类型的转换做什么的很好的信息,但这并不能帮助我弄清楚这种情况。使用 static_cast 和常规转换给我 error C2594: 'static_cast': ambiguous conversions from 'MyObject *' to 'ISerializable *'。使用 dynamic_cast 会导致 createObject() 返回 NULL。 NormalObject 样式类和旧版本的 MyObject 使用工厂中现有的 static_cast。

有没有办法让这个转换工作?看起来应该是可能的。

最佳答案

您必须虚拟地继承 ISerializable(我刚刚用 VS2010 对其进行了测试)。这是一个称为菱形继承(钻石问题)的常见问题,其中编译器不知道要采用哪个层次结构路径。

编辑:

应该这样做:

class NewAbstract : public virtual ISerializable { ... } 
class OldAbstract : public virtual ISerializable { ... } 

关于c++ - 无法转换具有多重继承的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2906500/

相关文章:

c++ - Win32 API 枚举 dll 导出函数?

c++ - 在函数 findx() 中是否有替代 const_cast<char*> 的方法?

laravel 5.6 id 自动转换为 int

c++ - 用专门的版本覆盖多个继承的模板函数

c# - 如何在页面和母版页之间共享代码而无需多重继承/代码重复?

java - 从子类的arraylist到达父类方法

c++ - 如何在我的 cpp 程序中使用这个宏?

c++ - 在派生模板类中重新实现基类的虚函数

c++ - 如何根据用户在c++中单击鼠标的位置旋转弹丸

java - 为什么在这种情况下向下转型会抛出 ClassCastException?