C++系列-函数对象/仿函数

函数对象/仿函数


李清照《声声慢·寻寻觅觅》

寻寻觅觅,冷冷清清,凄凄惨惨戚戚。乍暖还寒时候,最难将息。三杯两盏淡酒,怎敌他、晚来风急!雁过也,正伤心,却是旧时相识。

满地黄花堆积,憔悴损,如今有谁堪摘?守着窗儿,独自怎生得黑?梧桐更兼细雨,到黄昏、点点滴滴。这次第,怎一个愁字了得!


💢什么是仿函数

  • 🥝仿函数,即函数对象,并不是一个函数,它是与类相关的
  • 🥝一个类或者结构体的定义如果重载了()操作符,那么可以称为仿函数类,或者函数对象的类型。
  • 🥝仿函数类实例的对象,可以称为具体的函数对象,仿函数对象。
  • 🥝函数对象在使用上和函数非常相似(只针对于重载的()操作符)。

💢仿函数的使用

💢💢像普通函数一样使用

  • 🍓 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值

👉👉👉

在下面的代码中,MyPrint obj_print; 创建了一个函数对象,而它在使用()运算符时,像函数的调用。

string result = obj_print("Sure. when is it?"); ,可以有参数,可以有返回值。

cpp 复制代码
#include <iostream>
using namespace std;

template<class T>
void my_print(T& val)
{
	cout << val << " ";
}

template<class T>
class MyPrint
{
public:
	T operator()(const T& val)
	{
		cout << val << endl;
		return val;
	}
};

void test01()
{
	string s = "Can you come to my birthdat party?";
	my_print(s); // 使用普通的函数
	cout << endl;
	MyPrint<string> obj_print; // 创建函数对象
	// 函数对象在使用()重载成员函数时,像使用函数一样可以有参数,有返回值
	string result = obj_print("Sure. when is it?"); 
	cout << result << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
Can you come to my birthdat party?
Sure. when is it?
Sure. when is it?

💢💢可以有自己的状态

  • 🍉 函数对象在使用时,因为它本身是个对象,其成员,其它函数都可以正常使用,所以还可以记录状态

👉👉👉

在下面的代码中,m_count用来计数函数被调用过几次。

get_count()为状态提供了接口。

cpp 复制代码
code:
#include <iostream>
using namespace std;

template<class T>
class MyPrint
{
public:
	MyPrint()
	{
		m_count = 0;
	}
	T operator()(const T& val)
	{
		m_count++;
		cout << val << endl;
		return val;
	}
	int get_count()
	{
		return m_count;		// 可以用来记录状态
	}
private:
	int m_count;
};

void test01()
{
	MyPrint<string> my_print1; // 创建函数对象
	// 函数对象在使用()重载成员函数时,像使用函数一样可以有参数,有返回值
	for (int i_loop = 0; i_loop < 5; i_loop++)
	{
		my_print1("Orange is my favorite color.");
	}
	cout << "the numbers of the function call: " << my_print1.get_count() << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
Orange is my favorite color.
Orange is my favorite color.
Orange is my favorite color.
Orange is my favorite color.
Orange is my favorite color.
the numbers of the function call: 5

💢💢可以作为函数的参数

👉👉👉

在下面的代码中,my_print1作为print_func的参数。

因为函数对象它本身是个对象,它可以作为函数参数。

cpp 复制代码
code:
#include <iostream>
using namespace std;

template<class T>
class MyPrint
{
public:
	T operator()(const T& val)
	{
		cout << val << endl;
		return val;
	}
};

template<class T>
void print_func(MyPrint<T> &my_print, string info)
{
	my_print(info);
}

void test01()
{
	MyPrint<string> my_print1; // 创建函数对象
	// 函数对象作为参数
	print_func(my_print1, "It's on sunday.");
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
It's on sunday.

💢💢可以作为模板参数

👉👉👉

仿函数类可以作为模板参数。

因为它本身就是一种类型。

cpp 复制代码
code:
#include <iostream>
using namespace std;

class MyPrint
{
public:
	string operator()(const string & val)
	{
		cout << val << endl;
		return val;
	}
};

template<class T>
void print_func(T & my_print, string info)		// 
{
	my_print(info);
}

void test01()
{
	MyPrint my_print1; // 创建函数对象
	// 仿函数类作为模板参数
	print_func<MyPrint>(my_print1, "It starts at two o'clock in the afternoon.");
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
It starts at two o'clock in the afternoon.

💢💢可以作为容器相关的算法的参数

cpp 复制代码
code:
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

template<class T>
void my_print(T & val)
{
	cout << val << " ";
}


template<class T>
class MyPrint
{
public:
	MyPrint()
	{
		cout << "默认构造函数" << endl;
	}
	MyPrint(const int& val)
	{
		cout << "有参构造函数" << endl;
	}
	void operator()(T& val)
	{
		cout << val << " ";
	}
};

template<class T>
void print_vector(vector<T>& vec)
{
	for_each(vec.begin(), vec.end(), MyPrint<T>());
}

void test01()
{
	vector<int> vec1{1, 5, 56, 23, 11, 4};
	// MyPrint2<int>(10)是匿名对象,因为MyPrint2类中重载了操作符(),故MyPrint2<int>(10)是一个函数对象
	for_each(vec1.begin(), vec1.end(), MyPrint<int>(10));	
	cout << endl;
	vector<float> vec2{1.1, 5.5, 56.3, 23.8, 11.5, 4.7};
	// 对于for_each中的第三个参数,可以是普通的函数,也可以是函数对象
	for_each(vec2.begin(), vec2.end(), my_print<float>);
	cout << endl;

	// MyPrint2<int>()是匿名对象,因为MyPrint2类中重载了操作符(),故MyPrint2<int>()是一个函数对象
	for_each(vec2.begin(), vec2.end(), MyPrint<float>());
	cout << endl;
}

result:
有参构造函数
1 5 56 23 11 4
1.1 5.5 56.3 23.8 11.5 4.7
默认构造函数
1.1 5.5 56.3 23.8 11.5 4.7
相关推荐
大大dxy大大7 分钟前
机器学习-KNN算法示例
人工智能·算法·机器学习
喜欢吃燃面27 分钟前
C++:哈希表
开发语言·c++·学习
mit6.82428 分钟前
[C++] 时间处理库函数 | `tm`、`mktime` 和 `localtime`
开发语言·c++
SweetCode28 分钟前
C++ 大数乘法
开发语言·c++
listhi52038 分钟前
基于空时阵列最佳旋转角度的卫星导航抗干扰信号处理的完整MATLAB仿真
开发语言·matlab·信号处理
lly2024061 小时前
Kotlin 类和对象
开发语言
是苏浙1 小时前
零基础入门C语言之C语言内存函数
c语言·开发语言
zhmhbest1 小时前
Qt 全球峰会 2025:中国站速递 —— 技术中立,拥抱更大生态
开发语言·qt·系统架构
程序员大雄学编程1 小时前
用Python来学微积分30-微分方程初步
开发语言·python·线性代数·数学·微积分
关于不上作者榜就原神启动那件事1 小时前
模拟算法乒乓球
开发语言·c++·算法