c++ - 运算符 == 错误

标签 c++ class operators qvector

<分区>

我已经定义了一个类Point。我还有一个 PointCollection 类:class PointCollection: public QVector<Point>在这里实现一些方法时出现以下错误:

error: no match for 'operator==' (operand types are 'Point' and '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 类的私有(private)变量。在我定义的构造函数中:

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 必须知道如何比较 Points 是否相等(否则它如何找到 vector 中的点)。它为此使用了 operator==,但是您还没有为 Point 类编写 operator==,所以您会收到此错误。只需为 Point 编写 operator==(并且 operator!= 也是一个好主意)。

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

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

关于c++ - 运算符 == 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342321/

相关文章:

c++ - 在 3D 中查找垂直于两条相交线的点

c++ - 设置GL上下文时 'framebuffer'的目的是什么?

c++ - 优化模拟的 flatbuffer 字典

ios - 逻辑和按位运算符警告混淆 - iOS

c++ - ACE_SOCK_Dgram::open() 和 errno

class - Swift的实例方法和类型方法的区别

c++ - 为什么析构函数被调用两次而构造函数只被调用一次?

javascript - 如何确定 javaScript 中扩展运算符结果的数据类型?

javascript - 是什么 !! JavaScript 中的(不是 not)运算符?

java - 方法中的私有(private)类 - java