c++ - 如何克隆多个继承对象?

标签 c++ clone multiple-inheritance generic-programming cloneable

我已经定义了一个 Cloneable 接口(interface):

struct Cloneable
{
  virtual Cloneable * clone(void) const = 0;
}

我还有一些其他的接口(interface)类(内容与issue无关):

struct Interface
{
};

struct Useful_Goodies
{
};

我创建了一个继承自上述类的叶对象:

struct Leaf : public Cloneable, public Interface, public Useful_Goodies
{
  Leaf * clone(void) const  // Line #1 for discussion.
  {
     return new Leaf(*this);
  }
};

我收到错误:

overriding virtual function return type differs and is not covariant from 'Cloneable::clone'

如果我将类型更改为 Cloneable *,我会收到此错误消息:

'return' : ambiguous conversions from 'Leaf *' to 'Cloneable *'

我的问题(所有相关):

  1. 叶类如何解决 Cloneable 的要求 界面?
  2. 是否有更好的解决方案来实现 克隆合约,其中所有对象 是否保证实现克隆?

我将此范例用作通用编程(记录、字段和数据库)的一部分。

编译器:MS Visual Studio 2008;平台:Windows XP 和 Vista

最佳答案

让您的 clone 函数返回一个 Cloneable * 是正确的。

如果您的接口(interface)之一也派生自 Cloneable,您将得到一个不明确的转换。

编辑:Alf 在评论中指出,Leaf::clone 不仅可以返回 Leaf*,实际上最好这样做。我的立场是正确的。

关于c++ - 如何克隆多个继承对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944060/

相关文章:

c++ - 多态是实现这一目标的最佳方法吗? (关于派生类中的函数调用)

c++11 - C++中std::shared_ptr的克隆模式

将 Draggable 放入可排序后,jQuery Click 事件不起作用

c# - C++ 如何克服菱形问题?

python - 是否可以在 Python 中检测冲突的方法名称?

python - 有没有办法在 Python 的多重继承对象中访问重写的方法?

c# - 从 C++ 包装代码以在 C# 中使用

c++ - 切换高对比度模式时 CMFCMenuButton 无法正确重绘

类中的 C++ vector - 程序段错误

c# - 程序集中的类型未标记为可序列化