在 C 中复制多态对象

新手上路,请多包涵

我有基类 Base 派生自 Derived1Derived2Derived3

我已经为我存储为 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 许可协议

阅读 434
1 个回答

这仍然是我们在 C++ 中为多态类做事的方式,但是如果为对象创建复制构造函数(可能是隐式的或私有的),则不需要显式复制成员。

 class Base
{
public:
  virtual Base* Clone() = 0;
};

class Derivedn : public Base
{
public:
  //This is OK, its called covariant return type.
  Derivedn* Clone()
  {
    return new Derivedn(*this);
  }
private:
  Derivedn(const Derivedn&) : ... {}
};

原文由 Michael Anderson 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏