C++ 函数对象

C++中有一种类叫函数对象又称仿函数,到底什么是函数对象呢?

其实函数对象就是一个类实现了括号操作符重载,即称为函数对象、仿函数,因为它的对象可以像使用一个函数一样来使用。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Square
 5 {
 6 public:
 7     int operator()(int x) const { return x * x; }
 8 };
 9 
10 int main(int argc, char **argv)
11 {
12     int y = 0;
13     Square s;
14     y = s(5);
15 
16     cout << y << endl;
17     return 0;
18 }

上面代码中的Sqare类就是一个函数对象,可以看到它的对象可以像函数一样被使用。

原文地址:https://www.cnblogs.com/lit10050528/p/3884220.html