2013-05-06 28 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对象调用。