How to implement clone in a pure abstract class?
因此,我想在派生类中重写纯抽象方法,但出现此错误。 有人可以帮我看看发生了什么,如何完成。
我的
1 2 3 4 5 6 7 8 | class Device { public: Device(); Device(const Device& orig); virtual ~Device(); virtual Device Clone() = 0; } |
还有我的派生类;
1 2 3 4 5 6 7 8 | class Radar : public Device { public: Radar(); // Radar(const Radar& orig); // commenting so the compiler using its default copy constructor virtual ~Radar(); Radar Clone(); }; |
我的
1 2 3 | Radar Radar::Clone() { return *(new Radar(*this)); } |
如果我在
如果使用
我该怎么办?
您的
因此,应为:
1 | virtual Device* Clone() = 0; |
...然后...
1 2 3 4 5 6 7 | Radar* Clone(); // YES, it should be Radar* here - that uses C++'s support for //"covariant return types", see also"UPDATE" discussion Radar* Radar::Clone() { return new Radar(*this); } |
更新-根据要求提供进一步说明
因此,具有clone函数的想法是,它可以返回您的
希望这有助于澄清问题。您可能还需要对面向对象编程进行一些背景阅读。
实现此克隆技术的经典方法是对
协变返回类型的优点之一是,您可以获取对象的克隆(深层副本),并且返回类型与参数在层次结构中处于同一级别(即,返回并不总是返回基数)类),并且不需要立即进行强制转换。在C ++中,指针和引用支持协方差,值不支持协方差。
建议在原始画笔上使用诸如
该解决方案确实需要使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <type_traits> #include <utility> #include <memory> class Device { public: virtual Device* Clone() const = 0; }; class Radar : public Device { public: virtual Radar* Clone() const override { // ^^^^^^ covariant return compared to Device::Clone return new Radar(*this); } }; // Clone factory template <typename Class, typename T> std::unique_ptr<Class> clone_unique(T&& source) { static_assert(std::is_base_of<Class, typename std::decay<decltype(*source)>::type>::value, "can only clone for pointers to the target type (or base thereof)"); return std::unique_ptr<Class>(source->Clone()); } int main() { std::unique_ptr<Radar> radar(new Radar()); std::unique_ptr<Device> cloned = clone_unique<Device>(radar); } |
样例代码。
有关更长的示例,请参见此相关答案。
请尝试以下签名
虚拟设备&Clone()= 0;
要么
虚拟设备* Clone()= 0;
//身体
1 2 3 | Device& Radar::Clone() { return Radar(*this)); } |