【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;
}

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

相关推荐
whxnchy14 小时前
UDP多端口负载均衡实战
c++
叼烟扛炮15 小时前
C++ 知识点08 类与对象
开发语言·c++·算法·类和对象
楼田莉子15 小时前
仿Muduo的高并发服务器:Http协议模块
linux·服务器·c++·后端·学习
tjl521314_211 天前
04C++ 名称空间(Namespace)
开发语言·c++
ximu_polaris1 天前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式
wdfk_prog1 天前
正常关闭虚拟机时,不要点“关机”,而要点“关闭客户机”
linux·c语言·网络·ide·vscode
流年如夢1 天前
单链表 -->增、删、查、改等详细操作
c语言·数据结构
tankeven1 天前
C++ 智能指针
c++
handler011 天前
【算法模板】最小生成树:稠密图选 Prim,稀疏图选 Kruskal
c语言·数据结构·c++·算法
许长安1 天前
RPC 异步调用基本使用方法:基于官方helloworld-async 示例
c++·经验分享·笔记·rpc