Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用共享\u ptr基类型和共享\u ptr派生类型重写方法_C++_Polymorphism_Overriding_Smart Pointers_Covariant Return Types - Fatal编程技术网

C++ 使用共享\u ptr基类型和共享\u ptr派生类型重写方法

C++ 使用共享\u ptr基类型和共享\u ptr派生类型重写方法,c++,polymorphism,overriding,smart-pointers,covariant-return-types,C++,Polymorphism,Overriding,Smart Pointers,Covariant Return Types,我正在尝试创建一个抽象方法,用于克隆从base派生的类,并将它们作为共享\u ptr返回,如下所示: class Base { public: virtual std::shared_ptr<BaseSymbol> clone() = 0; }; class Derived : public Base { public: Derived(const Derived& derived); std::shared_ptr<Derived> cl

我正在尝试创建一个抽象方法,用于克隆从base派生的类,并将它们作为共享\u 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();
};
类基{
公众:
虚拟std::shared_ptr clone()=0;
};
派生类:公共基{
公众:
派生(常量派生和派生);
std::shared_ptr clone();
};

这给我带来了一个编译错误。我知道使用普通指针可以实现这一点,那么如何使用共享指针才能实现这一点呢?

协方差仅在使用指针/引用时才可能实现

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

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); }
};
类基{
公众:
std::shared_ptr clone()常量
{
返回std::shared_ptr(vclone());
}
virtual~Base()=默认值;
受保护的:
虚拟BaseSymbol*vclone()常量=0;
};
派生类:公共基{
公众:
派生(常量派生和派生);
std::shared_ptr clone()常量
{
返回std::shared_ptr(vclone());
}
受保护的:
派生*vclone()常量重写{返回新的派生(*this);}
};

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

相关/重复:至少使用
std::make_shared()
,并让虚拟方法返回共享的ptr。开发一个允许模板选择协方差的功能会很有意思…@重复数据消除程序:这需要使用:-/从
std::shared_ptr
std::shared_ptr
:-/@Jarrod42:在当前规则下,是的。但由于它们在结构上是等价的,人们可以改变规则。或者您的意思是更改为
std::make_shared()
?好吧,这一次演员阵容是值得的。@Deduplicator:是吗?我的评论确实是关于
std::make_shared
。允许将类型标记为协变可能很好。或者它们只是“自定义”指针。