我有基类 Base
派生自 Derived1
, Derived2
和 Derived3
。
我已经为我存储为 Base* a
的派生类之一构建了一个实例。我现在需要制作对象的深层副本,我将存储为 Base* b
。
据我所知,复制类的正常方法是使用复制构造函数并重载 operator=
。 However since I don’t know whether a
is of type Derived1
, Derived2
or Derived3
, I cannot think of a way of using复制构造函数或 operator=
。我能想到干净地完成这项工作的唯一方法是实现类似的东西:
class Base
{
public:
virtual Base* Clone() = 0;
};
并在派生类中实现 Clone
,如下所示:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Java 倾向于使用 Clone
相当多的 C++ 方法可以做到这一点吗?
原文由 doron 发布,翻译遵循 CC BY-SA 4.0 许可协议
这仍然是我们在 C++ 中为多态类做事的方式,但是如果为对象创建复制构造函数(可能是隐式的或私有的),则不需要显式复制成员。