Can I pass a pointer to a superclass, but create a copy of the child?(我可以将指针传递给超类,但创建子类的副本吗?)
问题描述
我有一个函数,它接受一个指向超类的指针并对其执行操作.但是,在某些时候,该函数必须对输入的对象进行深层复制.有什么办法可以进行这样的复制吗?
I have a function that takes a pointer to a superclass and performs operations on it. However, at some point, the function must make a deep copy of the inputted object. Is there any way I can perform such a copy?
我想到将函数设为模板函数并简单地让用户传递类型,但我希望 C++ 提供更优雅的解决方案.
It occurred to me to make the function a template function and simply have the user pass the type, but I hold out hope that C++ offers a more elegant solution.
推荐答案
SpaceCowboy 提出了惯用的 clone
方法,但忽略了 3 个关键细节:
SpaceCowboy proposes the idiomatic clone
method, but overlooked 3 crucial details:
class Super
{
public:
virtual Super* clone() const { return new Super(*this); }
};
class Child: public Super
{
public:
virtual Child* clone() const { return new Child(*this); }
};
clone
是一个const
方法clone
返回指向当前类的指针,而不是基类clone
返回当前对象的副本
clone
is aconst
methodclone
returns a pointer to the current class, not the base classclone
returns a copy of the current object
第二个非常重要,因为它可以让用户受益于这样一个事实,即有时您拥有比 Super*
更多的类型信息.
The 2nd is very important, because it allows use to benefit from the fact that sometimes you have more type information than just a Super*
.
另外,我通常更喜欢 clone
提供一个副本,而不仅仅是一个相同类型的新对象.否则,您正在使用 Exemplar
模式来构建新对象,但您没有正确克隆并且名称具有误导性.
Also, I usually prefer clone
to provide a copy, and not merely a new object of the same type. Otherwise you're using an Exemplar
pattern to build new objects, but you're not cloning proper and the name is misleading.
这篇关于我可以将指针传递给超类,但创建子类的副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以将指针传递给超类,但创建子类的副本吗?


基础教程推荐
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17