gpt4 book ai didi

c++ - 虚函数不返回具有多级继承的派生类型

转载 作者:搜寻专家 更新时间:2023-10-31 01:13:29 26 4
gpt4 key购买 nike

我有一个具有多级继承的类层次结构。

  1. cloneable 声明一个返回cloneable * 的纯虚成员函数。
  2. base 派生自 cloneable,但不声明任何成员函数。
  3. 最后,derived 派生自base 并定义了虚函数,但将返回类型覆盖为derived *

通过指向 derived 对象的 base 指针调用虚函数返回 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* 的版本? , 没有任何声明?


虽然上面的问题回答了你的直接问题,但我觉得我还应该添加一些建议。

首先,

  • clone函数 const , 这样就可以在 const 上调用它对象或通过右值表达式。

即,

virtual cloneable* clone() const;

其次,创建对象的克隆

  • 返回new T( *this ) (使用复制构造函数),而不是 new T (使用默认构造函数)。

第三,

  • 为了安全,为了公开可用 clone操作返回一个智能指针,例如 unique_ptr<MyClass> ,不是原始指针。

但是,随着返回类型更改为智能指针,您将不再直接受益于 C++ 对协变函数结果的支持,这仅适用于原始指针和引用。因此,一种方法是使用非 public原始指针结果实现,它可以具有协变结果类型,并且只是类型化的 public返回智能指针的包装器。实际上,您正在为公共(public)接口(interface)实现协方差,您自己,它看起来像这样:

#include <memory>       // std::unique_ptr
using namespace std;

class Base
{
private:
virtual Base* virtualClone() const
{
return new Base( *this );
}

public:
unique_ptr< Base > clone() const
{
return unique_ptr< Base >( virtualClone() );
}
};

class Derived
: public Base
{
private:
virtual Derived* virtualClone() const
{
return new Derived( *this );
}

public:
unique_ptr< Derived > clone() const
{
return unique_ptr< Derived >( virtualClone() );
}
};

int main()
{
Derived d;
Base* bp = &d;
unique_ptr< Base > bbp = bp->clone();
}

关于c++ - 虚函数不返回具有多级继承的派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com