随笔 - 322  文章 - 0  评论 - 4  阅读 - 77146

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   Bytezero!  阅读(58)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示