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

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

相关推荐
粉红色回忆12 小时前
用链表实现了简单版本的malloc/free函数
数据结构·c++
写代码的小球13 小时前
C++计算器(学生版)
c++·算法
k***921614 小时前
【C++】继承和多态扩展学习
java·c++·学习
序属秋秋秋14 小时前
《Linux系统编程之进程控制》【进程等待】
linux·c语言·c++·进程·系统编程·进程控制·进程等待
l木本I15 小时前
Reinforcement Learning for VLA(强化学习+VLA)
c++·人工智能·python·机器学习·机器人
strive programming15 小时前
Effective C++_异常(解剖挖掘)
c++
wregjru15 小时前
【读书笔记】Effective C++ 条款1~2 核心编程准则
java·开发语言·c++
lingran__16 小时前
C语言自定义类型详解 (1.1w字版)
c语言·开发语言
青岛少儿编程-王老师17 小时前
CCF编程能力等级认证GESP—C++1级—20251227
java·c++·算法
微露清风17 小时前
系统性学习C++进阶-第十四讲-二叉搜索树
开发语言·c++·学习