具有抽象类指针的对象的C ++副本 [英] C++ copies of objects with abstract class pointers

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

问题描述

考虑 Container 类,该类基本上存储了 Box 对象的 unique_ptr s向量,并可以对它们进行一些计算.

Consider the Container class, which basically stores a vector of unique_ptrs of Box objects and can perform some computations on them.

class Container
{
  private:
    std::vector<std::unique_ptr<Box> > boxes_;
  public:
    Container(std::vector<std::unique_ptr<Box> > &&boxes): boxes_(std::move(boxes)){}
    double TotalVolume() { /* Iterate over this->boxes_ and sum */ }
};

在这里, Box 是一个抽象类,它具有纯虚拟方法,例如 double Box :: Volume().

Here, Box is an abstract class that has a pure virtual method such as double Box::Volume().

现在,假设我在主程序中实例化一个容器为:

Now, suppose that I instantiate a container in the main program as:

std::vector<std::unique_ptr<Box> > x;
x.push_back(std::move(std::unique_ptr<Box>(new SquareBox(1.0)));
x.push_back(std::move(std::unique_ptr<Box>(new RectangularBox(1.0, 2.0, 3.0)));
Container c(x);

如何制作 c 的副本?我想要一个在 boxes _ 中创建基础 Box 对象的副本的函数,但是我认为使用基类很难做到这一点?

How do I make copies of c? I would like a function that makes copies of the underlying Box object in boxes_, but I think it's hard to do this with base classes?

推荐答案

制作副本的一种方法是在基类中使用"Copy"虚拟方法.此方法将创建当前对象的副本,并返回指向该对象的(唯一)指针.如果类中包含任何指针,则它们还需要创建新副本(深层副本).

One way to make your copies is to have a "Copy" virtual method in your base class. This method would create a copy of the current object and return a (unique) pointer to it. If there are any contained pointers within the class, they'd need new copies created as well (a deep copy).

存在其他方法.例如,您可以测试向量中的每个对象以确定其类型(使用 dynamic_cast ),但这很丑陋,效率低下并且容易出错.

Other approaches exist. For instance, you could test each object in the vector to determine its type (using dynamic_cast), but this is ugly, inefficient, and very error prone.

这篇关于具有抽象类指针的对象的C ++副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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