2013-08-20 119 views
1

我已經定義了一個類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類。在構造函數中,我定義:

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); 
} 
+2

你可以爲'Point'顯示'operator =='嗎? – juanchopanza

+1

'return(this [NearestPointToCentroidIndex]);'你真的想寫什麼? –

+0

@ juanchopanza:我很抱歉,但我沒有真正明白你的意思。 Point只是一個類,另一個類如下所示:class PointCollection:public QVector 。如果我的理解是正確的,operator ==應該是QVector的。 – Mike

回答

2

的問題是,爲了實施的indexOf,QVector必須知道如何比較積分相等(否則它怎麼能找到的點向量)。它使用運算符==爲此,但您沒有爲類Point寫入運算符==,所以您會收到此錯誤。只要寫點運算符==(和運算符!=也是個好主意)。

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

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

謝謝你的回答。 bool Point :: operator ==() { Point point =(Point)obj; if(this-> x == point.x && this-> y == point.y) { return(true); } return(false); }這是你的意思? – Mike

+2

這將是錯誤的。我的意思正是我寫的。沒有必要讓operator ==成爲一名班級成員,如果不是這樣,通常會更好。 – john

+0

謝謝你寶貴的答案 – Mike