我有此代码:
class allShapes {
private:
Shape ** _arr;
int _size;
public:
allShapes();
~allShapes();
int getSize() const;
void addShape(Shape * newShape);
allShapes operator+(const allShapes & other) const;
}
allShapes::~allShapes()
{
if (_arr != NULL)
{
for (int i = 0; i < getSize(); i++)
{
delete _arr[i];
_arr[i] = NULL;
}
delete[] _arr;
_arr = NULL;
}
};
allShapes allShapes::operator+(const allShapes & other) const
{
allShapes newallShapes;
for (int i = 0; i < getSize(); i++)
{
newallShapes.addShape(_arr[i]);
}
for (int i = 0; i < other.getSize(); i++)
{
newallShapes.addShape(other._arr[i]);
}
return newallShapes;
}
我的主:
allShapes shapes;
Circle * c1 = new Circle(3, "myCircle");
Circle * c2 = new Circle(2, "yourCircle");
shapes.addShape(c1);
shapes.addShape(c2);
allShapes newshape = shapes + shapes;
我的项目有问题:
有一些背景知识:我有allShapes,其中包含其他一些类,例如Circle和Square等。
我的操作员+有问题,
它将在方法中创建newallShapes良好,但随后在最后一行中:return newallShapes; 它调用析构函数,然后删除指针 newall形状并破坏一切!
我如何将带有所有指针的新“ newallShape”发回主机?