对派生类执行深层复制

low*_*owq 1 c++ polymorphism deep-copy

这最近一直困扰着我.假设我有一个基类Base.如果我在Base之上有多个派生类,例如DerivedA和DerivedB,那么深层副本就会变得很痛苦.

OtherClass(const OtherClass & _rhs)
{
    //I have a list of Base *, now I must assign a class id to each derived class to properly create a new one.
    //...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题?

tib*_*bur 9

您应该在Base类中定义克隆方法:

virtual Base * clone() const = 0;
Run Code Online (Sandbox Code Playgroud)

每个派生类都实现了克隆方法:

virtual DerivedA * clone() const {
    return new DerivedA(*this);
}
Run Code Online (Sandbox Code Playgroud)

然后你的OtherClass只需迭代并Base*在列表中的每个实例上调用clone方法.