简体   繁体   English

重载类中的<运算符

[英]overloading the < operator inside a class

I'm trying to use a simple structure as a map key: 我正在尝试使用一个简单的结构作为映射键:

class Foo{
 .
 .
 .
  struct index{
    int x;
    int y;
    int z;
  };

  bool operator<(const index a, const index b);
  .
  .
  .
}

And the function itslef: 和函数itslef:

bool Foo::operator<(const index a, const index b){
  bool out = True;
  if (a.x == b.x){
    if (a.y == b.y){
      if (a.z >= b.z) out = false;
    }
    else if(a.y > b.y) out = false;
  } else if (a.x > b.x) out = false;
  return out;
}

However, when I compile I get an error: 但是,当我编译时出现错误:

memMC.h:35: error: 'bool Foo::operator<(Foo::index, Foo::index)' must take exactly one argument memMC.h:35:错误:“ bool Foo :: operator <(Foo :: index,Foo :: index)”必须正好采用一个参数

As I understand this, the compilers wants to compare index to this Foo . 据我了解,编译器希望将index与此Foo进行比较。 How can I overload the operator then? 那我怎样才能使操作员超负荷?

If you want to compare two indexes, move the overload inside the index structure: 如果要比较两个索引,请在index结构内移动重载:

struct index{
    int x;
    int y;
    int z;
    bool operator<(const index& a) const;
};

If you want to compare a Foo and an index (I doubt that, but I'll just put this here just in case), remove the second parameter, as it's not needed: 如果要比较Fooindex (我对此表示怀疑,但是为了防万一,我将其放在此处),请删除第二个参数,因为它不是必需的:

class Foo{
  //...
  bool operator<(const index& a) const;
};

Note that you should pass the index parameter by reference, to prevent unnecesarry copying. 请注意,应通过引用传递index参数,以防止不必要的复制。

EDIT: As Als correctly pointed out, this operator should be const . 编辑:正如Als正确指出的,此运算符应为const

< is binary infix comparison operator ie it takes two arguments to compare to each other, So ideally it should be implemented as a free function, However if you implement it as a member function then it will take only one argument. <是二进制中缀比较运算符,即它需要两个参数进行相互比较,因此理想情况下应将其实现为自由函数,但是,如果将其实现为成员函数,则它将仅接受一个参数。

It shall compare the argument passed as parameter to the object on which the member function is being called. 它将比较作为参数传递的自变量与调用成员函数的对象。

Your member comparison operator should be like: 您的成员比较运算符应类似于:

class Foo
{
    //...
    bool operator<(const index& rhs) const 
    { 
        /* comparison with *this */ 
    }
    //...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM