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]

4

2 回答 2

1

您的函数需要一个const限定符:

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

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

于 2013-05-06T23:43:10.580 回答
1

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

class Vertex {
  // ...
  bool operator<(const Vertex& other) const;
  // ...
};
于 2013-05-06T23:43:17.740 回答