我有Base
派生的基类Derived1
,Derived2
和Derived3
.
我为其中一个派生类构建了一个实例,我将其存储为Base* a
.我现在需要制作一个我将存储的对象的深层副本Base* b
.
据我所知,复制类的正常方法是使用复制构造函数并重载operator=
.但是,因为我不知道是否a
是类型Derived1
,Derived2
或者Derived3
,我想不出使用复制构造函数的方法operator=
.我能想到的唯一方法是干净利落地完成这项工作:
class Base
{
public:
virtual Base* Clone() = 0;
};
Run Code Online (Sandbox Code Playgroud)
和Clone
派生类中的实现如下:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Run Code Online (Sandbox Code Playgroud)
Java倾向于使用Clone
相当多的C++方式更多吗?