一、概念
1、函数对象的概念:
- 重载函数调用操作符的类,其对象常称为函数对象。
- 函数对象使用重载的()时,行为类似函数调用,也叫仿函数。
- 函数对象(仿函数)是一个类,不是一个函数
2、函数对象使用
- 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
- 函数对象超出普通函数的概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<ctime>
using namespace std;
class MyAdd
{
public:
int operator()(int v1,int v2)
{
return v1 + v2;
}
};
// 1、函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
void Test01()
{
MyAdd myadd;
cout << myadd(10, 20) << endl;
}
// 2、函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
MyPrint()
{
count = 0;
}
void operator()(string strContent)
{
cout << strContent << endl;
count++;
}
int count;
};
void Test02()
{
MyPrint myprint;
myprint("this is just a test!");
myprint("some test");
cout << "myprint 被调用的次数为: " << myprint.count << endl;
}
// 3、函数对象可以作为参数传递
void DoPrint(MyPrint &mp,string test)
{
mp(test);
}
void Test03()
{
MyPrint my;
DoPrint(my, "hello this");
}
int main()
{
Test01();
Test02();
Test03();
system("pause");
}
二、谓词
- 返回 bool 类型的仿函数称为谓词。
- 如果 operator() 接受一个参数叫做一元谓词,两个参数叫做二元谓词。
1、一元谓词
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class GetValue
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void Test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
// GetValue() 在此为隐式对象
vector<int>::iterator it = find_if(v.begin(), v.end(),GetValue());
if (it != v.end())
{
cout << "找到了大于5的值 = " << (*it) << endl;
}
else
{
cout << "未找到大于5的值" << endl;
}
}
int main()
{
Test01();
system("pause");
}
三、内建函数对象
STL 中内建了一些函数对象。其分类为:
- 算术仿函数
- 关系仿函数
- 逻辑仿函数
这些仿函数所产生的对象、用法和一般函数完全相同。使用内建函数对象,需要引入头文件 #include<functional>
本文深入探讨了函数对象的概念,包括其定义、使用及如何作为参数传递,并详细讲解了一元谓词和二元谓词的功能与应用。通过具体代码示例,读者将了解函数对象如何模仿函数行为,同时保持类的特性,如拥有状态。此外,文章还介绍了STL中的内置函数对象及其分类。
881

被折叠的 条评论
为什么被折叠?



