我可以传递一个指向超类的指针,但创建一个孩子的副本? [英] Can I pass a pointer to a superclass, but create a copy of the child?

查看:81
本文介绍了我可以传递一个指向超类的指针,但创建一个孩子的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它接受一个指向超类的指针并对它执行操作。但是,在某些时候,函数必须对输入的对象进行深层复制。有什么办法可以执行这样的副本吗?

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); }
};




  1. clone const 方法

  2. clone 返回指向当前类的指针,不是基类

  3. clone 返回当前对象的副本

  1. clone is a const method
  2. clone returns a pointer to the current class, not the base class
  3. clone 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.

这篇关于我可以传递一个指向超类的指针,但创建一个孩子的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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