作用

  1. 函数调用运算符()也可以重载
  2. 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  3. 仿函数没有固定写法,非常灵活

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

class MyPrint {
public:

void operator()(string text) {
cout << text << endl;
}
};

class MyAdd {
public:
int operator()(int a,int b) {
return a + b;
}
};

void test01() {
MyPrint myPrint;
myPrint("Hello World");
}

void test02() {
MyAdd add;
int ret = add(10, 20);
cout << ret << endl;

//匿名对象函数
cout << MyAdd()(100, 200) << endl;
}

int main(){
test01();
test02();
return 0;
}