繁体   English   中英

抽象类中的c ++ clone函数

[英]c++ clone function in abstract class

在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>
};

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

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

我们做的是在Derived*分配Base* Derived* !!

问题
为什么这段代码不能编译? 为了适应继承,它怎么能被修改(以及为什么?)?

您发布的代码即使经过一些微不足道的编辑(我所做的)也无法编译。 Derived::clone()的签名应该是:

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

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

当您处理问题中所述的指针时,不会有任何切片。
Derived::clone()应该返回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); }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM