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

时间:2019-05-08 06:42:50

标签: c++

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

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

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

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

编辑:我添加了别人要求的其他方法:

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

}

  class allShapes {
  private:
   Shape ** _arr;
   int _size;

1 个答案:

答案 0 :(得分:0)

  

我做错了什么?

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

有两种可能使您难以出错。每个allShapes都有它自己拥有的每个Shape的副本,或者它们都共享所有权。最好通过前者std::unique_ptr<Shape>或后者std::shared_ptr<Shape>的集合来表达。

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
};
相关问题