我正在操纵定义如下的对象矢量:
class Hyp{
public:
int x;
int y;
double wFactor;
double hFactor;
char shapeNum;
double* visibleShape;
int xmin, xmax, ymin, ymax;
Hyp(int xx, int yy, double ww, double hh, char s): x(xx), y(yy), wFactor(ww), hFactor(hh), shapeNum(s) {visibleShape=0;shapeNum=-1;};
//Copy constructor necessary for support of vector::push_back() with visibleShape
Hyp(const Hyp &other)
{
x = other.x;
y = other.y;
wFactor = other.wFactor;
hFactor = other.hFactor;
shapeNum = other.shapeNum;
xmin = other.xmin;
xmax = other.xmax;
ymin = other.ymin;
ymax = other.ymax;
int visShapeSize = (xmax-xmin+1)*(ymax-ymin+1);
visibleShape = new double[visShapeSize];
for (int ind=0; ind<visShapeSize; ind++)
{
visibleShape[ind] = other.visibleShape[ind];
}
};
~Hyp(){delete[] visibleShape;};
};
当我创建一个Hyp对象时,将内存分配/写入visibleShape并将该对象添加到带有vector :: push_back的向量中,一切都按预期工作:visibleShape指向的数据使用copy-constructor复制。
但是当我使用vector :: erase从向量中移除Hyp时,其他元素被正确移动除了现在指向错误地址的指针成员visibleShape!如何避免这个问题?我错过了什么吗?
答案 0 :(得分:2)
我认为你错过了Hyp
重载的赋值运算符。
答案 1 :(得分:1)
我认为你可能会错过Hyp类中的赋值运算符=
。
Hyp& operator = (const Hyp& rhs);