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

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

相关推荐
进击的小头24 分钟前
常用数字滤波器的特性与适用场景
c语言·算法
txinyu的博客1 小时前
std::function
服务器·开发语言·c++
学嵌入式的小杨同学2 小时前
【嵌入式 C 语言实战】交互式栈管理系统:从功能实现到用户交互全解析
c语言·开发语言·arm开发·数据结构·c++·算法·链表
txinyu的博客2 小时前
static_cast、const_cast、dynamic_cast、reinterpret_cast
linux·c++
“αβ”2 小时前
TCP相关实验
运维·服务器·网络·c++·网络协议·tcp/ip·udp
孞㐑¥3 小时前
算法—滑动窗口
开发语言·c++·经验分享·笔记·算法
历程里程碑3 小时前
Linux 3 指令(3):进阶指令:文件查看、资源管理、搜索打包压缩详解
linux·运维·服务器·c语言·数据结构·笔记·算法
一分之二~3 小时前
二叉树--求最小深度(迭代和递归)
数据结构·c++·算法·leetcode·深度优先
C++ 老炮儿的技术栈3 小时前
KUKA机器人程序抓料
linux·运维·c语言·人工智能·机器人·库卡
zfxwasaboy4 小时前
DRM KMS 子系统(5)Device/demo
linux·c语言