Jay*_*dan 5 c++ casting multiple-inheritance virtual-inheritance
我试图重构一些代码,同时保留现有的功能.我无法将指向对象的指针转换为基接口,然后在以后获取派生类.在某些情况下,程序使用工厂对象来创建这些对象的实例.
以下是我正在使用的类的一些示例.
// 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
}
...
}
Run Code Online (Sandbox Code Playgroud)
这个问题很好地说明了不同类型的铸件的作用,但它并没有帮助我弄清楚这种情况.使用static_cast和常规投射给我error C2594: 'static_cast': ambiguous conversions from 'MyObject *' to 'ISerializable *'.使用dynamic_cast会导致createObject()返回NULL.NormalObject样式类和旧版MyObject与工厂中的现有static_cast一起使用.
有没有办法使这个演员工作?看起来应该是可能的.
Sim*_*mon 10
你必须从ISerializable 实际上继承(我只是用VS2010测试它).这是一个称为钻石问题的常见问题,编译器不知道要采用的层次结构路径.
编辑:
这应该这样做:
class NewAbstract : public virtual ISerializable { ... }
class OldAbstract : public virtual ISerializable { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3105 次 |
| 最近记录: |