首页 文章

operator()重载结构

提问于
浏览
2

我正在尝试在c中使用我的 Map 结构 . 结构很简单:

struct index{
  int x;
  int y;
  int z;
  bool operator<(const index &b){
    bool out = true;
    if ( x == b.x ){
      if ( y == b.y ){
        out = z < b.z;
      } else out = y < b.y;
    } else out = x < b.x;
    return out;
  }
};

但是当我编译时,我得到一个错误:

/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c /4.1.2/bits/stl_function.h:在成员函数'bool std中:: less <_Tp> :: operator()(const _Tp&,const _Tp&)const [with _Tp = membrane :: index]':/ usr / lib / gcc / x86_64 -redhat-linux /4.1.2 /../ ../../../include/c /4.1.2/bits/stl_map.h:347:从'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator []实例化(const _Key& )[with _Key = membrane :: index,Tp = std :: set,std :: less>,std :: allocator >>, Compare = std :: less,_Alloc = std :: allocator,std :: less>, std :: allocator>]'memMC.cpp:551:从这里实例化

据我所知,这意味着我需要重载()运算符 . 但是我不知道这个操作员通常做什么,所以我不知道如何正确覆盖它 . 维基百科告诉我,这是一个演员,但我不认为他们回归布尔......

我第一次尝试使用[]运算符访问 Map 元素时编译器崩溃 .

2 回答

  • 10

    尝试制作comaprison const:

    struct index{
      int x;
      int y;
     int z;
      bool operator<(const index &b) const
                                   //^^^^^ Missing this,
    
  • 4

    尝试免费过载:

    bool operator < (const index &a, const index &b)
    {
        if (a.x == b.x)
        {
            if (a.y == b.y)
            {
                return a.z < b.z;
            }
            else
            {
                return a.y < b.y;
            }
        }
        else
        {
            return a.x < b.x;
        }
    }
    

相关问题