[英]Having trouble when overloading the '<' operator for a map
我試圖重載'<'運算符,以便我可以在項目中使用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]
: /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]
你的函數需要一個const
限定符:
bool Vertex::operator <(const Vertex& other) const {
//...
}
這意味着它可以在const
對象上調用。
由於您的operator<
重載不修改對象指向this
,你應該把它標記為const
成員函數。 也就是說,對於聲明,在末尾添加一個const
:
class Vertex {
// ...
bool operator<(const Vertex& other) const;
// ...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.