【问题标题】:Vector of pointer to objects, need deep copy of vector, but the objects are the base of inherited objects指向对象的向量,需要向量的深拷贝,但对象是继承对象的基础
【发布时间】:2010-11-24 12:21:45
【问题描述】:

我想要一个带有指向对象的指针的向量的深层副本,但对象可以是 C 或 B。我知道令人困惑(我解释它的方式),让我举例说明。

class A {
    A(const A& copyme) { }
    void UnableToInstantiateMeBecauseOf() =0;
};

class B {
    B(const B& copyme) : A(copyme) {}
};

class C {
    C(const C& copyme) : A(copyme) {}
};

std::vector<A*>* CreateDeepCopy(std::vector<A*>& list)
{
    std::vector<A*>* outList = new std::vector<A*>();

    for (std::vector<A*>::iterator it = list.begin(); it != list.end(); ++it)
    {
        A* current = *it;
        // I want an copy of A, but it really is either an B or an C
        A* copy = magic with current;
        outList->push_back(copy);
    }

    return outList;
}

如何创建一个你不知道它是什么继承类型的对象的副本?

【问题讨论】:

    标签: c++ multiple-inheritance copy-constructor


    【解决方案1】:

    使用克隆:

    Copy object - keep polymorphism

    class Super
    {
    public:
        Super();// regular ctor
        Super(const Super& _rhs); // copy constructor
        virtual Super* clone() const = 0; // derived classes to implement.
    }; // eo class Super
    
    
    class Special : public Super
    {
    public:
        Special() : Super() {};
        Special(const Special& _rhs) : Super(_rhs){};
        virtual Special* clone() const {return(new Special(*this));};
    }; // eo class Special
    

    编辑:

    我在您的问题中注意到您的基类是抽象的。没关系,这个模型还能用,我已经修改了。

    【讨论】:

    • 复制构造函数在这里并不合适。通常,您选择其中之一:多态类或值类。
    【解决方案2】:

    为您的类添加一个虚拟 Clone() 方法。

    A* copy = it->Clone();
    
    class A {
        virtual A* Clone()
        {
            return new A(*this);
        }
    };
    

    在派生类中覆盖克隆。实现与A类相同。

    【讨论】:

      【解决方案3】:

      您可以在 A 类中实现纯虚拟克隆函数。

      【讨论】:

        【解决方案4】:

        正如其他人所说,您需要某种类型的克隆机制。您可能想查看 Kevlin Henney 在其出色论文 Clone Alone 中的 cloning_ptr

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-30
          • 2011-10-01
          • 1970-01-01
          • 2011-02-11
          • 2011-12-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多