我已经定义了一个 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 *'
我的问题(所有相关):
- 叶类如何解决
Cloneable
的要求 界面? - 是否有更好的解决方案来实现 克隆合约,其中所有对象 是否保证实现克隆?
我将此范例用作通用编程(记录、字段和数据库)的一部分。
编译器:MS Visual Studio 2008;平台:Windows XP 和 Vista
最佳答案
让您的 clone
函数返回一个 Cloneable *
是正确的。
如果您的接口(interface)之一也派生自 Cloneable
,您将得到一个不明确的转换。
编辑:Alf 在评论中指出,Leaf::clone
不仅可以返回 Leaf*
,实际上最好这样做。我的立场是正确的。
关于c++ - 如何克隆多个继承对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944060/