C++ //函数调用运算符重载 (仿函数)

 1 //函数调用运算符重载
 2 
 3 #include <iostream>
 4 #include <string>
 5 using namespace std;
 6 
 7 //函数调用运算符重载
 8 
 9 class MyPrint
10 {
11 public:
12 
13     //重载函数调用运算符
14     void operator()(string test)
15     {
16         cout << test << endl;
17     }
18 
19 };
20 
21 void MyPrint02(string test)
22 {
23     cout << test << endl;
24 }
25 
26 void test01()
27 {
28     MyPrint myprint;
29 
30     myprint("biubiubi");//由于使用起来像函数调用 因此称为 仿函数
31 
32     MyPrint02("nssidissd");
33 }
34 //仿函数非常灵活 没有固定写法
35 //加法类
36 
37 class MyAdd
38 {
39 
40 public:
41     int operator()(int num1, int num2)
42     {
43         return num1 + num2;
44     }
45 };
46 
47 
48 void test02()
49 {
50     MyAdd myadd;
51     int ret = myadd(100, 100);
52     cout << "ret = " << ret << endl;
53 
54     //匿名函数对象  当前行执行完了 立即被释放
55     cout << MyAdd()(100, 100) << endl;
56 }
57 int main()
58 {
59     test01();
60     test02();
61 }

 

posted on 2021-08-07 17:45  Bytezero!  阅读(85)  评论(0编辑  收藏  举报