问题将信息复制到指针阵列中



我有一个项目,我在其中创建了一个代表形状的抽象类。我有一个圆圈和四圈,从形状和正方形继承在四方面。最后,我有一个名为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;

我做错了什么?

您使用Shape **表示多个Shape衍生对象的所有权,并复制 pointers 。首先被销毁的allShapes对象将所有副本中的所有Shape * s无效。

有两种可能使错误的可能性。每个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
};

最新更新