【发布时间】:2015-10-28 16:50:11
【问题描述】:
我有一个基类和几个派生类。基类如下所示:
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() 方法的不同实现。)
【问题讨论】:
标签: c++ inheritance recursion deep-copy