2016-03-06 94 views
2

我有一個QList<MyPoint*> l其中MyPoint是用戶defiend類的類型,我想要做的:如何爲QList指針編寫自定義比較器?

QList<MyPoint*> l; 
MyPoint *a = new MyPoint(2, 4); 
MyPoint *b = new MyPoint(4, 8); 
MyPoint *c = new MyPoint(2, 4); 
l << a << b; 

則:

l.contains(c); //true 

我嘗試過載==運營商爲doc說:

此函數要求值類型具有 operator ==()的實現。

試過不同的方法,但似乎沒有按預期工作。

這裏是到目前爲止,我已經試過代碼:

class MyPoint 
{ 
public: 
    int x, y; 

    MyPoint(int x, int y) 
     : x(x), 
      y(y) 
    { 
    } 

    bool operator == (const MyPoint &other) const 
    { 
     return other.x == this->x && other.y == this->y; 
    } 

    bool operator == (const MyPoint *other) const 
    { 
     return true; 
    } 
}; 

bool operator == (const MyPoint &a, const MyPoint &b) 
{ 
    return a.x == b.x && a.y == b.y; 
} 

我想是這樣的:

bool operator == (const MyPoint *a, const MyPoint *b) 
{ 
    return a.x == b.x && a.y == b.y; 
} 

但我讀這是不可能的......我知道(*a == *c)爲真但我想這會影響行爲,以便使用我自己的比較器進行比較。

回答

2

operator == overloads只適用於MyPointer對象的指針地址,而不是對象本身。

而不是有一個MyPointer *對象列表,請嘗試製作一個MyPointer對象列表(即QList<MyPointer>)。你必須確保你重載賦值操作符和拷貝構造函數。

如果這變得太昂貴了,考慮轉換你的班級使用implicit sharing像大多數Qt數據類一樣使用QSharedDataQSharedDataPointer類。