C++:复制派生元素的树
C++: Duplicating a tree of derived elements
我有一个基类和几个派生类。基类如下:
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++编译器自动进行。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++ - 打印派生类对象的矢量<base*> 元素
- 继承函数是否适用于 C++ 中的基类元素或派生类元素?
- C++ 对矢量元素的调用函数,派生自矢量的基类
- 使用派生自 'std::tuple' 的元素在 'std::tuple' 上调用 'std::get' - 格式不正确
- 我怎么知道基类对象的指针数组中元素的类型,它将为派生类分配内存
- 派生类中的数据元素
- C 错误将派生的元素传递到方法
- std::tuple的实现是否允许在触发空类元素的派生到基转换时失败
- 基类的C++数组,该数组的元素中存储有派生类的实例
- 我需要制作一个包含基类和派生类的对象的向量,并知道哪个元素是哪个元素
- 将抽象基类上定义的向量的元素与具体的派生类进行匹配
- 在C++继承中,派生类如何禁用基类的某些元素(数据或函数)
- 哪个性能更快?具有 N 个派生类型的 vtable 查找,或具有 N 个元素的 std::map 查找
- 将具有指针的向量元素从一个派生类交换到另一派生类
- GStreatermm:通过从Gst::element派生创建一个新的元素类型(在插件中)
- 从指向基类型的指针向量,返回派生类型的第一个元素,该元素被强制转换为派生类型
- C++:复制派生元素的树
- 从Cocos2d::Layer派生的类有一个指针数据成员.这个元素也有一个向量容器.调用vector::push_bac
- 如何在c++中通过父类访问派生类的元素