我有一个项目,在这个项目中我创建了一个表示形状的抽象类。我有一个圆和一个四边形继承自一个形状和正方形继承自一个四边形。最后,我有一个名为allShapes的类,它有一个由Shape **指针及其大小组成的多态数组。
我需要实现+运算符,它接收一个allShapes对象并返回一个新的allShape,其中所有元素都位于this和other。
当我复制这个部分时,复制是正确的,但当我从其他部分复制部分时,我认为它没有复制,因为当函数完成时,当涉及到销毁时,我跳到一个错误,我正在尝试删除空白内容。我做错什么了?
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;发布于 2019-05-08 15:23:21
我做错了什么?
您使用Shape **来表示多个Shape-derived对象的所有权,并复制指针。无论哪个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
};https://stackoverflow.com/questions/56034949
复制相似问题