【C/C++】仿函数

  • 函数调用运算符 () 也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活

示例:

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


class MyPrint
{
public:
	//重载的运算符是"()",(string text)是参数列表。
	void operator()(string text)
	{
		cout << text << endl;
	}

};
void test01()
{
	//重载的()操作符 也称为仿函数
	MyPrint myFunc;
	myFunc("hello world");
}


class MyAdd
{
public:
	//重载的运算符是"()",(int v1, int v2)是参数列表。
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//MyAdd()是匿名对象,当前行执行完,立即被释放。
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {

	test01();
	test02();

	system("pause");

	return 0;
}

由于使用起来非常类似于函数的调用,因此称为仿函数。

相关推荐
Morwit1 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
OliverH-yishuihan2 小时前
开发linux项目-在 Windows 上 基于“适用于 Linux 的 Windows 子系统(WSL)”
linux·c++·windows
七禾页丫2 小时前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
wifi chicken2 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
zmzb01033 小时前
C++课后习题训练记录Day56
开发语言·c++
编程小Y3 小时前
C++ Insights
开发语言·c++
南棱笑笑生3 小时前
20251224给飞凌OK3588-C开发板适配Rockchip原厂的Buildroot【linux-6.1】系统时确认ssh服务【内置dropbear】
linux·c语言·ssh·rockchip
王老师青少年编程4 小时前
csp信奥赛C++标准模板库STL案例应用5
c++·stl·set·集合·标准模板库·csp·信奥赛
历程里程碑4 小时前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
Tipriest_4 小时前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法