zl程序教程

您现在的位置是:首页 >  后端

当前栏目

函数对象--仿函数

对象 函数 --
2023-09-14 09:02:34 时间

概念:

  • 重载调用函数操作符的类,其对象称为函数对象
  • 函数对象使用重载()时,行为类似函数调用,也叫仿函数

函数对象本质是一个类,不是一个函数

函数对象使用:
features:
在这里插入图片描述
1.函数对象在调用时,可以像普通函数一样调用,可以有参数,可以有返回值

#include<iostream>
using namespace std;
#include<string>
//函数对象
//1.函数对象在调用时,可以像普通函数一样调用,可以有参数,可以有返回值
class add {
public:
	int operator()(int a,int b)
	{
		return a + b;
	}
};
void test()
{
	add ADD;
	cout << ADD(125, 125) << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述
2.函数对象超出普通函数的概念,函数对象可以有自己的概念

#include<iostream>
using namespace std;
#include<string>
//函数对象
//2.函数对象超出普通函数的概念,函数对象可以有自己的概念
class add {
public:
	void operator()(string txt)
	{
		cout << txt << endl;
		count++;
	 }
	int count;
};
void test()
{
	add A;
	A.count = 0;
	A("函数对象");
	A("函数对象");
	A("函数对象");
	cout << A.count << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

3.函数对象可以作为参数传递

#include<iostream>
using namespace std;
#include<string>
//函数对象
//3.函数对象可以作为参数传递
class add {
public:
	void operator()(string txt)
	{
		cout << txt << endl;
		count++;
	 }
	int count;
};
void txt(add& A, string txt)
{
	A(txt);
}
void test()
{
	add A;
	A("函数对象做参数传递");
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述