【问题标题】:c++ : how can i overload < operator correctly? [duplicate]c++:如何正确重载 < 运算符? [复制]
【发布时间】:2019-10-30 13:51:22
【问题描述】:

我需要std::set&lt;std::pair&lt;int,NodeA&gt;&gt;。所以我需要重载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

C:\Users\cristina\Desktop\università pdf\Laboratorio di Programmazione\progetti c++_SFML_openGL\SFML-2019-4-Grid\NodeA.h|24|注:候选:bool NodeA::operator>

【问题讨论】:

  • bool operator&lt;(const NodeA&amp; a) { -> bool operator&lt;(const NodeA&amp; a) const {?
  • [Tangent] 如果您使用if(condition) return true; else return false;,请改用return condition;
  • 为什么你需要这一套?是用来做什么的?您需要解决的实际问题是什么?也许有更好的解决方案?
  • 您用于std::set 的类型以及您插入其中的方式看起来好像您真的想要std::mapstd::vector。不过,你还没有展示它是如何使用的,所以我不能确定。
  • 你的operator&lt;需要修改对象吗?如果没有,您的operator&lt; 是否标记为const

标签: c++ set


【解决方案1】:

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

此参考表明,作为成员函数operator&lt; 具有以下格式:

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

您需要标记您的运算符定义const,因为C++ 希望您保证仅&lt; 运算符不会更改所涉及的对象,并且将使用声明为const 的类的实例。

所以您在运算符的重载函数中缺少关键字const。你必须写:

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

如果你有兴趣知道 c++ 的代码到底在哪里提到了这一点,你可以看看这个 StackOverFlow 答案:https://stackoverflow.com/a/23927045/7865858

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    相关资源
    最近更新 更多