摘要中的 c++ 克隆函数 class

c++ clone function in abstract class

在c++11标准中,如果class B继承自class A,那么'B is an 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>
};

我们从 Derived 返回了一个指向 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 class 中 clone() 的 return 类型不同,但它是 virtual 的有效覆盖函数,因为 co-variance 在 C++ 中是合法的。

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

clone() 是否应该 virtual 取决于设计,但使用 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); }
};