c++ - 调用基类克隆实现

标签 c++ c++11 polymorphism clone

尝试实现克隆模式,但坚持函数调用顺序:

我有一个 Base 类,其中包含一个多态类 vector (脚本)。

类实现了一个克隆函数,该函数本质上是复制其自身及其所有成员(mScripts vector )。

Derived 类也实现了它自己的克隆函数版本,并负责其成员的克隆。目前只是一个整数。

问题:我应该如何调用Base类的克隆函数,在Derived类的克隆函数中,让每个类负责克隆自己的成员?

作为一个丑陋的解决方法,现在,我所有派生类的克隆函数手动执行 mScripts vector 克隆,基本上重复相同的代码。

class Base
{
public:

    virtual std::unqique_ptr<Base> clone()
    {
        std::unique_ptr<Base> clonedInstance = std::make_unique<Base>();

        //clone the underlying vector
        for(int i = 0; i < mScripts.size(); ++i)
        {
            clonedInstance->mScripts.push_back(std::move(mScripts[i]->clone()));
        }

        return std::move(clonedInstance);
    }

    std::vector<std::unique_ptr<ScriptBase>>    mScripts;   //polymorphic array
};



class Derived : public Base
{
public:

    Derived(const int x) : Base(), mX(x)
    {
    }

    std::unqique_ptr<Base> clone()
    {
        //calling base::clone() here?

        return std::unique_ptr<Base> clonedInstance = std::make_unique<Derived>(mX);
    }

private:

    int mX;

};

最佳答案

正确实现复制构造函数,那么每个克隆函数就是return std::make_unique<Derived>(*this);

class Base
{
public:
    Base() = default;
    Base(const Base& rhs) // default is not fine here
    {
        for (const auto& script : rhs.mScripts)
        {
            mScripts.push_back(script->clone());
        }
    }
    virtual ~Base() = default;

    virtual std::unique_ptr<Base> clone() const
    {
        return std::make_unique<Base>(*this);
    }

    std::vector<std::unique_ptr<ScriptBase>> mScripts;   //polymorphic array
};

class Derived : public Base
{
public:
    Derived(int x) : Base(), mX(x) {}
    Derived(const Derived&) = default; // Default is fine here

    std::unique_ptr<Base> clone() const override
    {
        return std::make_unique<Derived>(*this);
    }

private:
    int mX;
};

关于c++ - 调用基类克隆实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50351476/

相关文章:

c++ - c++ 编译的 DLL 可以在没有大小差异的情况下在代码上有所不同吗?

c++ - 无法解决错误 : non-const lvalue reference to type 'bool' cannot bind to a temporary of type 'bool'

c++ - CGAL - 制作时时钟转动?

Java多态练习

java - 构建命令失败,外部 native 问题 android studio

c++ - 导出函数转发给自己?

c++ - 带模板类的任意个参数赋值

C++。加权 std::shuffle

java - Java中的泛型类型——高级多态性

python - sqlalchemy 与 `len(query.all())` 和 `query.count()` 不同的值