使用 shared_ptr 基类型和 shared_ptr 派生类型覆盖方法

Override method with shared_ptr Base type with shared_ptr Derived type

我正在尝试创建一个抽象方法来克隆从 base 派生的 类 并将它们作为 shared_ptr 返回,如下所示:

class Base {
public:
    virtual std::shared_ptr<BaseSymbol> clone() = 0;
};
class Derived : public Base {
public:
    Derived(const Derived& derived);
    std::shared_ptr<Derived> clone();
};

这是一个编译错误。我知道这可以通过普通指针实现,那么我怎样才能让它与共享指针一起工作?

协方差仅适用于 pointer/reference。

对于智能指针,您必须“复制”接口:

class Base {
public:
    std::shared_ptr<Base> clone() const
    {
        return std::shared_ptr<Base>(vclone());
    }

    virtual ~Base() = default;
protected:
    virtual BaseSymbol* vclone() const = 0;
};
class Derived : public Base {
public:
    Derived(const Derived& derived);

    std::shared_ptr<Derived> clone() const
    {
        return std::shared_ptr<Derived>(vclone());
    }
protected:
    Derived* vclone() const override { return new Derived(*this); }
};

CRTP 可能有助于避免重写相同的模式。