C++ STL函数对象 仿函数

 1 //STL函数对象  仿函数
 2 #include<iostream>
 3 #include<string>
 4 
 5 using namespace std;
 6 
 7 
 8 //1.函数对象在使用时,可以向普通函数那样调用,可以有参数,可以有返回值
 9 class Myadd
10 {
11 public:
12     int operator()(int v1, int v2)
13     {
14         return v1 + v2;
15     }
16 };
17 void test01()
18 {
19     Myadd myadd;
20     cout << myadd(10, 10) << endl;
21 }
22 //2.函数对象超出普通函数的概念,函数对象可以有自己的状态
23 class Myprint
24 {
25 public:
26     Myprint()
27     {
28         this->count = 0;
29     }
30     void operator()(string test)
31     {
32         cout << test << endl;
33         this->count++;
34     }
35 
36     int count; ///内部自己状态
37 };
38 void test02()
39 {
40     Myprint myprint;
41     myprint("zhenglei ");
42     myprint("zhenglei ");
43     myprint("zhenglei "); 
44     myprint("zhenglei ");
45     myprint("zhenglei ");
46 
47     cout << "Myprint调用的次数= " << myprint.count << endl;
48 }
49 //3函数对象可以作为参数来传递
50 void doPrint(Myprint&mp,string test)
51 {
52     mp(test);
53 }
54 void test03()
55 {
56     Myprint myPrint;
57     doPrint(myPrint, "zhenglei");
58 }
59 
60 int main()
61 {
62     test01();
63     test02();
64     test03();
65     system("pause");
66     return 0;
67 }

 

posted on 2021-08-16 18:02  Bytezero!  阅读(55)  评论(0编辑  收藏  举报