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

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

相关推荐
无能者狂怒9 小时前
YOLO C++ Onnx Opencv项目配置指南
c++·opencv·yolo
集智飞行10 小时前
c++函数传参的几种推荐方式
开发语言·c++
点云SLAM11 小时前
C++ Template(模板)解读和模板报错如何“逆向阅读”定位
c++·c++20·c++模版·c++高级应用·c++模版报错定位
明洞日记12 小时前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
kingmax5421200812 小时前
《数据结构C语言:单向链表-链表基本操作(尾插法建表、插入)》15分钟试讲教案【模版】
c语言·数据结构·链表
农夫山泉2号12 小时前
【c++】——c++编译的so中函数有额外的字符
java·服务器·c++
仰泳的熊猫13 小时前
1077 Kuchiguse
数据结构·c++·算法·pat考试
mit6.82413 小时前
[box64] 解决ARM64运行x86_64跨平台兼容性 | 机器架构配置
c语言
喵了meme14 小时前
C语言实战6
c语言·开发语言
Logic10114 小时前
C程序设计(第五版)谭浩强 第七章课后习题优化算法与核心步骤解析
c语言·visualstudio·程序员·学习笔记·软件开发·编程基础·c语言入门