C++: Deep copying a Base class pointer(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++:深度复制基类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:深度复制基类指针
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
