首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将信息复制到指针数组时出现问题

将信息复制到指针数组时出现问题
EN

Stack Overflow用户
提问于 2019-05-08 14:42:50
回答 1查看 62关注 0票数 1

我有一个项目,在这个项目中我创建了一个表示形状的抽象类。我有一个圆和一个四边形继承自一个形状和正方形继承自一个四边形。最后,我有一个名为allShapes的类,它有一个由Shape **指针及其大小组成的多态数组。

我需要实现+运算符,它接收一个allShapes对象并返回一个新的allShape,其中所有元素都位于this和other。

当我复制这个部分时,复制是正确的,但当我从其他部分复制部分时,我认为它没有复制,因为当函数完成时,当涉及到销毁时,我跳到一个错误,我正在尝试删除空白内容。我做错什么了?

代码语言:javascript
运行
复制
allShapes allShapes::operator+(const allShapes & other) const 
{
    allShapes newS;
    newS._size = (this->getSize() + other.getSize());
    int k = 0;
    newS._arr = new Shape*[newS.getSize()];

    for (int i = 0; i < this->getSize(); i++)
    {
        newS._arr[i] = this->_arr[i];
    }

    for (int j = this->getSize(); j < newS.getSize(); j++)
    {
        newS._arr[j] = other._arr[k++]; //i think here is the problem
    }
    return newS;
}

编辑:我添加了别人询问的其他方法:

代码语言:javascript
运行
复制
 allShapes::allShapes(const allShapes & other) //copy constructor
 {
this->_size = other.getSize();
this->_arr = new Shape*[other.getSize()];
for (int i = 0; i < other.getSize(); i++)
{
    this->_arr[i] = other._arr[i];
}
  }


 allShapes::~allShapes()//destructor to all elements
{
    if (this->_arr != NULL)
{
    for (int i = 0; i < this->_size; i++)
    {
        delete this->_arr[i];
    }
    delete[] this->_arr;
}

}

代码语言:javascript
运行
复制
  class allShapes {
  private:
   Shape ** _arr;
   int _size;
EN

回答 1

Stack Overflow用户

发布于 2019-05-08 15:23:21

我做错了什么?

您使用Shape **来表示多个Shape-derived对象的所有权,并复制指针。无论哪个allShapes对象首先被销毁,都会使另一个副本中的所有Shape *无效。

有两种可能会让它很难出错。要么每个allShapes都有它自己的每个Shape的副本,要么它们都共享所有权。对于前者,最好是通过std::unique_ptr<Shape>集合来表达,对于后者,最好是通过std::shared_ptr<Shape>集合来表达。

代码语言:javascript
运行
复制
class allShapes {
  private:
   std::vector<std::shared_ptr<Shape>> data;
  public:
   allShapes operator+(const allShapes & other)
   {
    allShapes copy = *this;
    copy.data.insert(copy.data.end(), other.data.begin(), other.data.end());
    return copy;
   }
   // compiler generated special members are correct
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56034949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档