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

标签 c++ c++11 inheritance clone

在 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::clone()的签名应该是:

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

即使 clone() 的返回类型在BaseDerived类不同,它是对 virtual 的有效覆盖功能,因为 co-variance在 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); }
};

关于抽象类中的c++克隆函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28273777/

相关文章:

java - 为什么java类不从实现的接口(interface)继承注释?

javascript - 如何调用backbone中父模型的默认方法

c++ - 异步操作的 Asio 处理程序不会被调用,而它们的同步对应项可以正常工作

c++ - 如何访问 CMake 中的源文件名?

c++ - Vim 以纯配色方案为 cpp 上色

c++ - 创建的字符串如何从函数传回

c++ - 是否存在具有表达式 'C++11' 的有效 C++11 程序?

通过引用传递的 C++0x 初始化列表

c++ - 具有包扩展的可变参数函数模板不在最后一个参数中

C# - 从基本方法完成返回