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

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

相关推荐
云和数据.ChenGuang3 小时前
Ascend C 核心技术特性
c语言·开发语言
kyle~6 小时前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
NiNi_suanfa9 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
信奥胡老师10 小时前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺10 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
star _chen10 小时前
C++实现完美洗牌算法
开发语言·c++·算法
繁星星繁11 小时前
【C++】脚手架学习笔记 gflags与 gtest
c++·笔记·学习
CQ_YM11 小时前
数据结构之队列
c语言·数据结构·算法·
路痴楷11 小时前
无法定位程序输入点问题
c++·qt·visual studio
Source.Liu12 小时前
【LibreCAD】 RS_Units 类完整解析
c++·qt·rust