2
我有一个具有多级继承的类层次结构。虚拟函数不返回具有多级继承的派生类型
cloneable
声明一个返回cloneable *
的纯虚拟成员函数。base
来自cloneable
,但未声明任何成员函数。- 最后,
derived
来自base
并定义了虚函数,但是将返回类型覆盖为derived *
。
通过base
调用虚函数指针指向derived
对象返回cloneable *
。我期待base *
,因为虚函数的实现返回derived *
可转换为base *
。这里发生了什么?
如果我在base
中声明纯虚函数,我终于可以从它得到base *
,但我不明白为什么这个声明是必要的。
代码:
struct cloneable
{
virtual cloneable * clone() = 0;
};
struct base : cloneable
{
// virtual base * clone() = 0; // this line resolves the compile error
};
struct derived : base
{
virtual derived * clone() { return new derived; }
};
int main(int, char**)
{
derived d;
base * bp = &d;
base * bbp = bp->clone(); // error: invalid conversion
// from ‘cloneable*’ to ‘base*’
return 0;
}
注:我故意省略了虚析构函数缩短代码示例。
你说得对。我认为编译器会隐式地在'base'中声明一个纯虚函数,但即使它确实可能不会覆盖返回类型。所以宣言是必要的。你的三点是有效的:我需要添加const,但是我在“生产”代码中做了一个适当的克隆。我仍然在查看返回unique_ptr的示例代码。很有帮助。谢谢。 – svetianov