如大家所熟悉的,重载 operator() 是 C++ 中一种特殊机制,允许类的对象像函数一样被调用。这种对象被称为 函数对象(functor) 或 仿函数。
核心要点
- 语法形式 :在类中定义名为
operator()的成员函数。 - 调用方式 :对象名后跟圆括号,如
obj(arg1, arg2),等价于调用obj.operator()(arg1, arg2)。

这里需要提到一个词:仿函数。就是让一个类能够像函数一样的进行使用。具体做法就是重载函数,再通过具体的类对象进行调用即可。
为什么说是像函数一样调用呢?请看下面的例子:
#include <algorithm>
#include <iostream>
class Cmp {
public:
bool operator()(const int& a, const int& b) {
return a < b;
}
};
int main(void) {
// 定义一个零时对象
// 并像函数一样调用
if (Cmp()(1, 2)) {
std::cout << "1 < 2" << std::endl;
} else {
std::cout << "1 >= 2" << std::endl;
}
}
回到我们的 的例子,我们只需要放入一个仿函数对象即可。
#include <algorithm>
#include <climits>
#include <vector>
class Cmp {
public:
bool operator()(const int& a, const int& b) {
return a < b;
}
};
int main(void) {
std::vector<int> arr = {INT_MAX, INT_MIN, -1, 0, 1};
// 传入一个具体的对象
Cmp cmpobj;
std::sort(arr.begin(), arr.end(), cmpobj);
}