C++:深度复制基类指针

C++: Deep copying a Base class pointer(C++:深度复制基类指针)
本文介绍了C++:深度复制基类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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{}

然后我又上了一节课:

class DeepCopy 
{ 
  Base * basePtr;

  public:
   DeepCopy(DeepCopy & dc) {}
}

假设 Base 类和 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_casts 似乎不对.另外需要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?

推荐答案

你需要使用virtual copy 模式:在接口中提供一个虚函数来进行复制,然后跨平台实现层次结构:

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++:深度复制基类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)