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

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

相关推荐
郭源潮142 分钟前
《Muduo网络库:实现TcpServer类终章》
服务器·网络·c++·网络库
liebe1*12 小时前
C语言程序代码(四)
c语言·数据结构·算法
chao1898444 小时前
C 文件操作全解速览
服务器·c语言·c#
MMjeaty4 小时前
查找及其算法
c++·算法
青光键主4 小时前
C语言内功强化之const修饰指针
c语言·开发语言
yong15858553435 小时前
1. Linux C++ muduo 库学习——库的编译安装
linux·c++·学习
mit6.8245 小时前
回溯剪枝trick
c++
hazy1k6 小时前
51单片机基础-TFT LCD 显示(ILI9341,SPI 4线)
c语言·stm32·单片机·嵌入式硬件·51单片机
渡我白衣6 小时前
C++世界的混沌边界:undefined_behavior
java·开发语言·c++·人工智能·深度学习·语言模型
却道天凉_好个秋6 小时前
c++ 协程
c++