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

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

相关推荐
m0_734998016 分钟前
Day 26
数据结构·c++·算法
爱编码的小八嘎31 分钟前
C语言完美演绎6-4
c语言
Summer_Uncle1 小时前
【QT学习】Qt界面布局的生命周期和加载时机
c++·qt
小CC吃豆子1 小时前
C++ 继承
开发语言·c++
励志的小陈1 小时前
复杂度算法题——旋转数组(三种思路)
c语言·数据结构·算法
tankeven1 小时前
HJ151 模意义下最大子序列和(Easy Version)
c++·算法
fengenrong2 小时前
20260325
开发语言·c++
BestOrNothing_20152 小时前
从C++结构体、类到 PID 控制器:运动控制初学者如何理解 C++ 工程代码
c++·面向对象·pid·运动控制·.h与.cpp·struct与class
㓗冽2 小时前
2026.03.27(第三天)
数据结构·c++·算法
Rooting++2 小时前
C 位域的作用
c语言