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

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

相关推荐
特立独行的猫a6 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
YXXY3136 小时前
模拟实现map和set
c++
阿猿收手吧!6 小时前
【C++】引用类型全解析:左值、右值与万能引用
开发语言·c++
「QT(C++)开发工程师」6 小时前
C++ 策略模式
开发语言·c++·策略模式
似霰6 小时前
Linux timerfd 的基本使用
android·linux·c++
三月微暖寻春笋7 小时前
【和春笋一起学C++】(五十八)类继承
c++·派生类·类继承·基类构造函数·派生类构造函数
热爱编程的小刘7 小时前
Lesson05&6 --- C&C++内存管理&模板初阶
开发语言·c++
czy87874757 小时前
深入了解 C++ 中的 Lambda 表达式(匿名函数)
c++
CSDN_RTKLIB7 小时前
include_directories和target_include_directories说明
c++
Trouvaille ~8 小时前
【Linux】UDP Socket编程实战(二):网络字典与回调设计
linux·运维·服务器·网络·c++·udp·操作系统