我相信这个问题的答案非常简单,但我就是无法让这个东西正常工作。我基本上创建了两个类;一种用于点,一种用于多边形。多边形由点的动态列表组成。
但是,当我尝试重载点类中的 + 运算符并使其返回两个点的多边形时,我会在关闭控制台窗口后得到一些奇怪的输出和“调试断言失败”。
下面是 + 运算符的重载方法:
CPolygon CPoint::operator + (CPoint pointToAdd) {
CPolygon polygon;
polygon.addPoint(this);
polygon.addPoint(pointToAdd);
cout << polygon.toString();
return polygon;
}
当我现在尝试使用此方法时,例如,我得到以下输出:
(5, 2, 3) - (1, 1, 2)
(444417074, -33686019, , -1555471217) - (-1424299942, 0, 0)
输出的第一行来自方法本身,而第二行来自多边形返回的位置。
我真的不知道我的多边形对象在从方法内部到返回调用代码的过程中发生了什么。
如果有人能给我一些关于这个的见解,我将非常感激:)
编辑
以下是多边形类的 addPoint 方法:
void CPolygon::addPoint(CPoint pointToAdd) {
nrOfPoints++;
// Create a temp array of the new size
CPoint * tempPoints = new CPoint[nrOfPoints];
// Copy all points to the temp array
for(int i = 0; i < (nrOfPoints - 1); i++) {
tempPoints[i] = points[i];
}
// Add the new point to the end of the array
tempPoints[nrOfPoints - 1] = pointToAdd;
// Delete the old array and set the temp array as the new array
delete[] points;
points = tempPoints;
}
void CPolygon::addPoint(CPoint * pointToAdd) {
addPoint(* pointToAdd);
}