操作员过载'operator()'

Operator Overloading 'operator()'

本文关键字:operator 操作员      更新时间:2023-10-16

我正在实现Dijkstra的算法,我想使用STL的'priority_queue'来加快编码过程,但是就像我尝试用C++编码一样,我对语言的缺乏理解正在减慢我的速度。我在 http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/找到了这个例子,但不明白以下内容在做什么:

// constructing priority queues
#include <iostream>
#include <queue>
using namespace std;
class mycomparison
{
  bool reverse;
public:
  mycomparison(const bool& revparam=false)
    {reverse=revparam;}
  bool operator() (const int& lhs, const int&rhs) const
  {
    if (reverse) return (lhs>rhs);
    else return (lhs<rhs);
  }
};
int main ()
{
  int myints[]= {10,60,50,20};
  priority_queue<int> first;
  priority_queue<int> second (myints,myints+4);
  priority_queue< int, vector<int>, greater<int> > third (myints,myints+4);
  // using mycomparison:
  priority_queue< int, vector<int>, mycomparison > fourth;
  typedef priority_queue<int,vector<int>,mycomparison> mypq_type;
  mypq_type fifth (mycomparison());
  mypq_type sixth (mycomparison(true));
  return 0;
}

更具体地说,"bool operator()(const int&lhs, const int&rhs) const"是让我绊倒的原因。其余的我很好。我认为它重载了运算符,但"operator()"对我来说毫无意义。任何帮助将不胜感激。

本质上,operator()"只是"另一个可以重载的运算符,因此您所知道的有关运算符重载的所有内容仍然适用 - 它很有用,因为它可以应用于具有与调用函数相同的语法的对象,例如

MyClass f;
f(); // i.e. f.operator()();

也就是说,除此之外,关于函子等还有很多话可以说 - 你可能想在谷歌上搜索函子/函数对象以获取更多信息。这是一个链接:

http://en.wikipedia.org/wiki/Function_object

在上面的代码中,priority_queue采用一个比较函子,它用来对你放入队列的内容进行排序。第一个队列(fifth)使用正常排序;第二个队列(sixth)使用反向排序。

这是函数调用运算符,你可以像这样使用它:

mycomparison mycomp;  //defines an object
mycomp(1,2);  // invokes operator()(int,int)
bool operator () ( const int &, const int & );

这是一个函数,operator()的重载,它接受两个整数并返回一个布尔值。 const表示无法更改该值。它代表常量