重载地图的'<'运算符时出现问题

Having trouble when overloading the '<' operator for a map

本文关键字:问题 lt 地图 重载 运算符      更新时间:2023-10-16

我试图重载'<'操作符,以便我可以在项目中使用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]

因为你的operator<重载不修改this所指向的对象,你应该把它标记为const成员函数。也就是说,对于声明,在末尾添加一个const:

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

您的函数需要const限定符:

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

这意味着它可以在const对象上调用