我定义了一个可克隆的接口:
struct Cloneable
{
virtual Cloneable * clone(void) const = 0;
}
我还有一些其他接口类(与发布无关的内容):
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;Platform: Windows XP & Vista
发布于 2010-10-15 16:23:06
让您的clone
函数返回一个Cloneable *
是正确的。
如果您的一个接口也是从Cloneable
派生的,您将得到一个不明确的转换。
编辑: Alf在评论中指出,Leaf::clone
不仅可以返回Leaf*
,而且实际上最好这样做。我被纠正了。
发布于 2010-10-15 17:28:31
您可能没有提到Interface
或其他一些基类也继承了Cloneable
。“模棱两可的转换”意味着Leaf
可能包含多个Cloneable
基类子对象。(协变量返回类型的问题可能是同一问题的直接结果。)
您将希望使用虚拟继承解决这个问题(推荐并链接阅读: C++ FAQ主题25.8至25.13)。首先,将: public Cloneable
的所有实例更改为: public virtual Cloneable
。
发布于 2010-10-15 17:28:32
我可以冒险并说,您可能实际上不是从多个路径从Cloneable
继承来的。也就是说,除了直接Cloneable
之外,其他一些基础继承了(直接或间接) Cloneable
。这使得从Leaf*
到Cloneable*
的转换变得模棱两可,因为Leaf
中有多个Cloneable
基。
简单的解决方案是使用来自接口的虚拟继承:
struct Cloneable {
virtual Cloneable * clone() = 0;
};
struct Interface : virtual Cloneable {
};
struct Test : virtual Cloneable, Interface {
virtual Test* clone() {
return new Test(*this);
}
};
虚拟继承意味着,即使Interface
和Test
都是从Cloneable
继承的,也只有一个Cloneable
基对象。
https://stackoverflow.com/questions/3944060
复制相似问题