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

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

相关推荐
zfxwasaboy5 小时前
DRM KMS 子系统(4)Planes/Encoder/Connector
linux·c语言
暮色_年华6 小时前
随想 2:对比 linux内核侵入式链表和 STL 非侵入链表
linux·c++·链表
极客代码6 小时前
深入解析C语言中的函数指针:原理、规则与实践
c语言·开发语言·指针·状态机·函数·函数指针
敲皮裤的代码6 小时前
《C语言》分支和循环(下)
c语言
w-w0w-w7 小时前
C++模板参数与特化全解析
开发语言·c++
大锦终8 小时前
递归回溯综合练习
c++·算法·深度优先
喵了meme8 小时前
c语言经验分享
c语言·开发语言
晚风吹长发8 小时前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法
风之歌曲9 小时前
c++高精度模板
c++·算法·矩阵
crescent_悦9 小时前
C++:Find Coins
c++