2013-05-06 43 views
0

我想重載'<'運算符,以便我可以在項目中使用std :: map。在類定義中的原型是這樣的:bool operator<(const Vertex&);,和函數體看起來是這樣的:在爲地圖重載'<'運算符時遇到問題

bool Vertex::operator <(const Vertex& other){ 
    //incomplete, just a placeholder for now 
    if(px != other.px){ 
     return px < other.px; 
    } 
    return false; 
} 

,我得到的錯誤是這樣的:/usr/include/c++/4.7/bits/stl_function.h:237:22: error: passing ‘const Vertex’ as ‘this’ argument of ‘const bool Vertex::operator<(Vertex)’ discards qualifiers [-fpermissive]

+0

不平等檢查不應該有所作爲,因爲'PX chris 2013-05-06 23:57:00

+0

函數不完整,如果px相同,我繼續下一個成員變量以確定差異。 – AdamSpurgin 2013-05-07 00:10:17

+1

如果情況並非如此,我無法抗拒指出。無論如何,現在你已經說過了,你應該使用'std :: make_pair'或者'std :: tie'這樣的東西來將這兩個因素組合在一起(例如'std :: make_pair(px,py) chris 2013-05-07 00:15:08

回答

1

由於您的operator<過載不修改this指向的對象,因此應將其標記爲const成員函數。也就是說,在聲明中,添加一個const到最後:

class Vertex { 
    // ... 
    bool operator<(const Vertex& other) const; 
    // ... 
}; 
+0

謝謝,就是這樣。 – AdamSpurgin 2013-05-06 23:47:55

1

你的函數需要一個const預選賽:

bool Vertex::operator <(const Vertex& other) const { 
    //... 
} 

這意味着它可以在const對象調用。