C ++:深度复制Base类指针 [英] C++: Deep copying a Base class pointer

查看:170
本文介绍了C ++:深度复制Base类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处搜索,似乎为了执行此操作,我需要更改我的Base类,并想知道这是否是最好的方法。
例如,
我有一个基类:

I searched around and seems in order to perform this I need to change my Base class and want to know if this is the best approach. For example, I have a Base class:

class Base {}

然后是一长串派生类:

class Derived_1:: public Base {}
class Derived_2:: public Derived_1{}
...
...
class Derived_n:: public Derived_M{}

然后我还有另一个班级:

And then I have another class:

class DeepCopy 
{ 
  Base * basePtr;

  public:
   DeepCopy(DeepCopy & dc) {}
}

假设Base class和Derived_x类复制构造函数已正确编码,那么为DeepCopy编写复制构造函数的最佳方法是什么。我们怎么知道我们要复制的对象的basePtr中的类?

Assuming the Base class and Derived_x class copy constructors are properly coded, what is the best way to write the copy constructor for DeepCopy. How can we know about the class that is in the basePtr of the object we are going to copy?

我能想到的唯一方法是使用RTTI,但使用一长串的dynamic_cast似乎不对。此外,它需要DeepCopy来了解Base类的继承层次结构。

Only way I can think of is using RTTI, but using a long list of dynamic_casts seems not right. Besides it requires DeepCopy to know about the inheritance hierarchy of Base class.

我看到的另一种方法是此处。但是它需要Base和Derived类实现一个克隆方法。

The other method I saw is here. But it requires Base and Derived classes implement a clone method.

那么有一个更简单,标准的方法吗?

So is there a much easier, standard way of doing this?

推荐答案

您需要使用虚拟副本模式:在执行复制的接口中提供虚拟功能,然后跨层次结构实现它:

You need to use the virtual copy pattern: provide a virtual function in the interface that does the copy and then implement it across the hierarchy:

struct base {
   virtual ~base() {}                // Remember to provide a virtual destructor
   virtual base* clone() const = 0;
};
struct derived : base {
   virtual derived* clone() const {
      return new derived(*this);
   }
};

然后 DeepCopy 对象只需要调用该函数:

Then the DeepCopy object just needs to call that function:

class DeepCopy 
{ 
  Base * basePtr;    
public:
   DeepCopy(DeepCopy const & dc)           // This should be `const`
      : basePtr( dc.basePtr->clone() )
   {}
};

这篇关于C ++:深度复制Base类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆