代码之家  ›  专栏  ›  技术社区  ›  Stormenet

指向对象的指针的向量,需要向量的深度复制,但这些对象是继承对象的基础

  •  4
  • Stormenet  · 技术社区  · 14 年前

    我想有一个向量的深度副本,上面有指向对象的指针,但是对象可以是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;
    }
    

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

    4 回复  |  直到 14 年前
        1
  •  4
  •   Community agent420    7 年前

    使用克隆:

    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
  •  2
  •   frast    14 年前

    向类中添加虚拟clone()方法。

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

    重写派生类中的克隆。实现与类A相同。

        3
  •  2
  •   Andreas Brinck    14 年前

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

        4
  •  2
  •   Daniel Lidström    14 年前

    正如其他人所说,您需要某种类型的克隆机制。您可能想查看 cloning_ptr 凯夫林·亨尼在他出色的论文中 Clone Alone .