C++:如何正确地重载 < 运算符?

3

我需要一个 std::set<std::pair<int,NodeA>>。因此,我需要重载 NodeA 的 < 运算符。我已经这样做了,但是它没有起作用。

void matriceLab::aStar(int* matX,const int x, const int y, const int endX,const int endY){
    std::set<std::pair<int,NodeA>> nodi;
    allocaNodi(nodi,matX,x,y,endX,endY);


}
void matriceLab::allocaNodi(std::set<std::pair<int,NodeA>>& nodi, int* matX,const int x, const int y,const int endX,const int endY){
    for(int i = 0; i < x; i++){
        for(int j = 0; j < y; j = j + 2){
            NodeA nodo(i,j,endX,endY);
            std::pair <int,NodeA> pair1(i + j * x, nodo);
            nodi.insert(pair1);
        }
    }
}

class NodeA
{
//...
       bool operator<(const NodeA& a){
            if(posX < a.posX){
                return true;
            }else{
                return false;
            }
        }
//...
}

C:\TDM-GCC-32\lib\gcc\mingw32\5.1.0\include\c++\bits\stl_pair.h|222|错误:没有匹配的'operator<'(操作数类型为'const NodeA'和'const NodeA')|

C:\Users\cristina\Desktop\università pdf\Laboratorio di Programmazione\progettic++_SFML_openGL\SFML-2019-4-Grid\NodeA.h|24|注意:候选项:bool NodeA::operator<(const NodeA&) <<近似匹配>>


7
bool operator<(const NodeA& a) { 翻译为 bool operator<(const NodeA& a) const { 的意思是在函数声明中添加 const 修饰符,表示该函数不会修改对象的成员变量。 - Algirdas Preidžius
2
【建议】如果你使用 if(condition) return true; else return false;,可以直接使用 return condition; - NathanOliver
你为什么需要这个集合?它的用途是什么?你需要解决的实际问题是什么?也许有更好的解决方案吗? - Some programmer dude
你所使用的类型及插入方式似乎更适合 std::mapstd::vector,而非 std::set。但由于没有展示其具体用途,我不能确定。 - walnut
你的 operator< 是否需要修改对象?如果不需要,你的 operator< 是否标记为 const - Eljay
1个回答

2

参考文献:https://en.cppreference.com/w/cpp/language/operator_comparison

这个参考文献说,作为成员函数operator< 的格式如下:

bool T::operator <(const T2 &b) const;

由于C++要求您承诺仅使用<运算符不会改变涉及的对象,并且将与声明为const的类实例一起工作,因此您需要标记运算符定义为const

因此,在运算符重载函数中缺少关键字const。您需要编写:

bool operator<(const NodeA& a) const{
        if(posX < a.posX){ ...

如果您想知道c++的代码具体在哪里提到这一点,您可以查看这篇StackOverFlow答案:https://dev59.com/xoDba4cB1Zd3GeqPASIV#23927045


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接