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

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

相关推荐
hazy1k22 分钟前
ESP32基础-Socket通信 (TCP/UDP)
c语言·单片机·嵌入式硬件·网络协议·tcp/ip·udp·esp32
dvvvvvw25 分钟前
x的y次幂的递归函数.c
c语言
FuckPatience1 小时前
C++ 常用类型写法和全称
开发语言·c++
__BMGT()1 小时前
参考文章资源记录
开发语言·c++·qt
ouliten2 小时前
C++笔记:std::string_view
开发语言·c++·笔记
玫瑰花店2 小时前
万字C++中锁机制和内存序详解
开发语言·c++·算法
D_evil__2 小时前
[C++高频精进] 文件IO:文件流
c++
西幻凌云2 小时前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器
Elias不吃糖3 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
Want5953 小时前
C/C++跳动的爱心②
c语言·开发语言·c++