运算符==错误

Operator == error

本文关键字:错误 运算符      更新时间:2023-10-16

我定义了一个类Point。我还有一个类PointCollection:class PointCollection: public QVector<Point>在实现一些方法时,我会得到以下错误:

错误:"operator=="不匹配(操作数类型为"Point"answers"const Point")

这是我出现此错误的代码部分:

    Point PointCollection::getNearestPointToCentroid()
{
    float minDist = 0.0;
    int NearestPointToCentroidIndex = -1;
    while(!this->empty())
    {
        Point point;
        Point centroid;
        float dist = PointT.calculateEuclideanDist(point, centroid);
        if(this->indexOf(point) == 0)
        {
            minDist = dist;
            NearestPointToCentroidIndex = this->indexOf(point);
        }
        else
        {
            if(minDist > dist)
            {
                minDist = dist;
                NearestPointToCentroidIndex = this->indexOf(point);
            }
        }
    }
    return(this[NearestPointToCentroidIndex]);
}

其中:Point centorid;float X;float Y;int Id;是PointCollection类的私有变量。在构造函数中,我定义:

PointCollection::PointCollection()
{
    //centorid = new Point;
    Id = PointT.GetId();
    X = PointT.GetX();
    Y = PointT.GetY();
}

float Point::calculateEuclideanDist(Point point_1, Point point_2)
{
    float x1 = point_1.x, y1 = point_1.y;
    float x2 = point_2.x, y2 = point_2.y;
    float dist = qSqrt(qPow(x2 - x1, 2.0) + qPow(y2 - y1, 2.0));

    return (dist);
 }

问题是,为了实现indexOf,QVector必须知道如何比较相等的点(否则如何在向量中找到点)。它使用了运算符==,但您还没有为类Point编写运算符==。因此会出现此错误。只需为Point写运算符==(和运算符!=也是个好主意)。

bool operator==(const Point& x, const Point& y)
{
    // your code here
}
bool operator!=(const Point& x, const Point& y)
{
    return !(x == y);
}