1

我相信这个问题的答案非常简单,但我就是无法让这个东西正常工作。我基本上创建了两个类;一种用于点,一种用于多边形。多边形由点的动态列表组成。

但是,当我尝试重载点类中的 + 运算符并使其返回两个点的多边形时,我会在关闭控制台窗口后得到一些奇怪的输出和“调试断言失败”。

下面是 + 运算符的重载方法:

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);
}
4

3 回答 3

1

我按照 PlasmaHH 和 urzeit 上面的建议做了,并为多边形类实现了复制构造函数,你猜怎么着,它解决了问题!:) 感谢所有帮助我的人!

多边形类的复制构造函数如下所示:

CPolygon::CPolygon(const CPolygon & polygon) :
    nrOfPoints(polygon.nrOfPoints)
{
    points = new CPoint[nrOfPoints];

    // Add all the points from the polygon to be copied
    for(int i = 0; i < nrOfPoints; i++) {
        points[i] = polygon.points[i];
    }
}
于 2013-10-09T10:05:49.187 回答
0

你的代码:

CPolygon CPoint::operator + (CPoint pointToAdd) {
    CPolygon polygon;


    polygon.addPoint(this);
    polygon.addPoint(pointToAdd);

    cout << polygon.toString();

    return polygon;
}

我觉得奇怪的是, polygon.addPoint(this)你正在添加一个指向 的指针CPolygon,因为this它是一个指针。你应该polygon.addPoint(*this)改用吗?在polygon.addPoint(pointToAdd)您通过价值或参考添加。

如果您需要进一步的帮助,请添加 function 的所有原型CPolygon::addPoint

于 2013-10-09T09:16:46.437 回答
-1

您的多边形对象是在堆栈上声明的,在操作员作用域之后您将失去对它的引用!

尝试声明它:

CPolygon* polygon = new Polygon(...);

您的签名应如下所示:

CPolygon* CPoint::operator + (CPoint pointToAdd) 

确实使用原始指针是一个坏主意,您必须在范围之外照顾它,更好的解决方案是用户智能指针:

std::auto_ptr<CPolygon> CPoint::operator + (CPoint pointToAdd) 
{
    std::auto_ptr<CPolygon> polygon(new CPolygon);
    // do stuff here
    return polygon;
}

// ...

{
  std::auto_ptr<CPolygon> polygon = firstPoint + secondPoint;
  // working with CPolygon

  // auto_ptr frees polygon 
}
于 2013-10-09T09:30:17.123 回答