1 c++ polymorphism copy object
我想用c ++复制对象.问题是我已经派生出具有多态性的类,如下面的伪代码所示:
class BaseCl { some virtual functions };
class DerivedClass : public BaseCl { ... };
Run Code Online (Sandbox Code Playgroud)
...
BaseCl * b1 = new DerivedClass();
BaseCl * b2 = new "copy of b1"; (just pseudocode)
Run Code Online (Sandbox Code Playgroud)
问题是最后一行:
我想复制类"BaseCl"的对象,但由于多态性,副本必须与"DerivedClass"的原始对象一样.
最好的方法是什么?
非常感谢,任何帮助表示赞赏.
编辑:问题已解决:
插入:
virtual BaseCl *clone() = 0;
Run Code Online (Sandbox Code Playgroud)
在基类和
DerivedCl *clone() {return new DerivedCl(*this);}
Run Code Online (Sandbox Code Playgroud)
在派生类中.谢谢你们.
您需要在BaseC1中定义一个进行克隆的函数.就像是:
class BaseCl
{
virtual BaseCl* clone() {return new BaseC1(*this);}
};
class DerivedClass : public BaseCl
{
virtual BaseCl* clone() {return new DerivedClass(*this);}
};
Run Code Online (Sandbox Code Playgroud)