【问题标题】:Operator == error [closed]运算符 == 错误 [关闭]
【发布时间】:2013-08-20 18:22:17
【问题描述】:

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

错误:'operator==' 不匹配(操作数类型为 'Point' 和 '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);
 }

【问题讨论】:

  • 您能否为Point 显示您的operator==
  • return(this[NearestPointToCentroidIndex]); 真的是你要写的吗?
  • @juanchopanza:很抱歉,我没有真正理解你的意思。 Point 只是一个类,另一个类如下:类 PointCollection:public QVector。如果我的理解是正确的,operator== 应该是 QVector 的。
  • @Jonathan Wakely:是的,我需要有质心的索引。
  • 哪一行产生了错误?

标签: c++ class operators qvector


【解决方案1】:

问题在于,为了实现 indexOf,QVector 必须知道如何比较 Points 是否相等(否则它如何找到向量中的点)。它为此使用 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);
}

【讨论】:

  • 感谢您的回答。 bool Point::operator==() { Point point = (Point)obj; if (this->x == point.x && this->y == point.y) { return (true); } 返回(假); } 这就是你的意思吗?
  • 那是错误的。我的意思正是我写的。没有必要让 operator== 成为类成员,如果不这样做通常会更好。
  • 感谢您的宝贵回答
猜你喜欢
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多