抽象类中的 C++ 克隆函数

c++ clone function in abstract class

本文关键字:函数 C++ 抽象类      更新时间:2023-10-16

在 C++11 标准中,如果类 B 继承自类 A,则"B 是 A"。但是,我仍然对这个概念感到困惑:看看这个代码:

class Base {
public: 
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};
class Derived : public Base {
public:
    virtual Base* clone() const {
        return new Derived(*this);
    }
    //<more functions>
};

我们从派生返回了一个指向 Base 的指针,但如果在此代码中使用此方法:

Derived* d1 = new Derived();
Derived* d2 = d1->clone();

我们所做的是在Derived*中分配Base*

问题:
为什么这段代码不能编译?如何修改它(为什么?)以适应继承?

即使经过一些琐碎的编辑(我所做的),您发布的代码也无法编译。Derived::clone()的签名应为:

virtual Derived* clone() const override {  // <-- return type
  return new Derived(*this);
}

尽管 BaseDerived类中clone()的返回类型不同,但它是virtual函数的有效覆盖,因为协方差在C++是合法的。

当您处理问题中所述的指针时,不会有任何切片。
Derived::clone()应该返回Derived*.

是否应该virtual clone()取决于设计,但使用virtual析构函数是个好主意。


另一种方法是使用template并避免virtual

class Base {
public: 
    virtual ~Base() {}
    template<class T>  // now need not add this trivial code in all derived classes
    T* clone() const { return new T(*this); }
};