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

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

相关推荐
sycmancia1 小时前
C语言学习03——数据类型
c语言
明洞日记3 小时前
【CUDA手册002】CUDA 基础执行模型:写出第一个正确的 Kernel
c++·图像处理·算法·ai·图形渲染·gpu·cuda
oioihoii3 小时前
程序员如何系统入门Vibe Coding?
c++
C+++Python3 小时前
C++类型判断
开发语言·c++
黎雁·泠崖4 小时前
整数的N进制字符串表示【递归+循环双版满分实现】
c语言·开发语言
张张努力变强4 小时前
C++类和对象(一):inline函数、nullptr、类的定义深度解析
开发语言·前端·jvm·数据结构·c++·算法
oioihoii4 小时前
C++线程编程模型演进:从Pthread到jthread的技术革命
java·开发语言·c++
小美单片机4 小时前
Proteus 报错 Unable to open HEX file ‘..\1、程序\jio\jtd.hex‘. [U1]
c语言·单片机·嵌入式硬件·51单片机·proteus
雾岛听蓝5 小时前
理解C++多态
开发语言·c++