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

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

相关推荐
ZouZou老师几秒前
C++设计模式之解释器模式:以家具生产为例
c++·设计模式·解释器模式
无限进步_22 分钟前
深入理解 C/C++ 内存管理:从内存布局到动态分配
c语言·c++·windows·git·算法·github·visual studio
JANGHIGH32 分钟前
c++ 多线程(三)
开发语言·c++
点云SLAM1 小时前
C++ 中traits 类模板(type traits / customization traits)设计技术深度详解
c++·算法·c++模板·c++高级应用·traits 类模板·c++17、20·c++元信息
liu****1 小时前
9.二叉树(一)
c语言·开发语言·数据结构·算法·链表
铁手飞鹰2 小时前
[HAL库分析—GPIO]
c语言·stm32·单片机·嵌入式硬件
水饺编程2 小时前
第3章,[标签 Win32] :处理 WM_PRINT 消息
c语言·c++·windows·visual studio
虚假程序设计2 小时前
pythonnet 调用C接口
c语言·python
慕容青峰3 小时前
【LeetCode 1925. 统计平方和三元组的数目 题解】
c++·算法·leetcode
哈哈xcpc-43993 小时前
天梯赛题解(Python和C++解法)
开发语言·c++·python