C++:复制派生元素的树

C++: Duplicating a tree of derived elements

本文关键字:元素 派生 复制 C++      更新时间:2023-10-16

我有一个基类和几个派生类。基类如下:

class Base
{
    int type; //the derived type the object belongs to
    int nOfChildren;
    Base** children; //each child can be any of the derived types
    ...
}

现在我需要复制Base的一个实例。由于递归,需要一个虚拟方法Base::duplicate()。似乎也很清楚应该包含什么:

Base temp = new Base();
temp->type = temp;
temp->nOfChildren = nOfChildren;
temp->children = new Base*[nOfChildren];

除此之外,还不太清楚。

我是将每个temp->children[i]分配为Base对象还是作为派生对象?我是否需要一个case语句来满足所有可能的派生类型?我是否需要为每个派生类型实现一个duplicate()方法,即使是那些除了基类之外不包含其他信息的派生类型?(如果派生类包含更多信息,那么很明显我需要一个单独的机制。有几个派生类除了基本类之外不包含其他数据,尽管它们包含未显示的handler()方法的不同实现。)

没错,需要一个虚拟方法来克隆多态对象。OTOH,您可以利用C++功能简化编写:

class Child : public ICloneable {
public:
    // stuff...
    Child *clone() const { return new Child(*this); }
}

另外,不要将对象集合放入数组中!请改用std::vector

class Base
{
    // stuff...
    std::vector<Base*> children;
}

更好的是,使用智能指针将克隆操作封装到std::vector能够透明管理的对象中。

template<typename T>
struct clone_ptr {
    T *object;
    clone_ptr() : object(new T()) {}
    clone_ptr(T *object_) : object(object_) {}
    clone_ptr(clone_ptr<T> const &other) : object(other.object->clone()) {}
    clone_ptr<T> &operator=(clone_ptr<T> other) {
        std::swap(object, other.object);
        return *this;
    }
    ~clone_ptr() { delete object; }
};

这样,你就可以在你的基地中使用clone_ptrs中的std::vector

class Base
{
    // stuff...
    std::vector<clone_ptr<Base>> children;
}

只要在每个类中实现clone(),每个对象都会自动复制到相同多态类型的对象中。向量将以与其他数据成员相同的方式进行克隆,由C++编译器自动进行。