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

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

相关推荐
雾岛听蓝13 小时前
红黑树深度解析:设计原理与实现逻辑
c++
gjxDaniel13 小时前
A+B问题天堂版
c++·算法·字符串·字符数组
M__3314 小时前
动态规划进阶:简单多状态模型
c++·算法·动态规划
米优14 小时前
使用Qt实现消息队列中间件动态库封装
c++·中间件·rabbitmq
N.D.A.K14 小时前
CF2138C-Maple and Tree Beauty
c++·算法
AI视觉网奇14 小时前
ue 5.5 c++ mqtt 订阅/发布 json
网络·c++·json
程序员-King.14 小时前
day159—动态规划—打家劫舍(LeetCode-198)
c++·算法·leetcode·深度优先·回溯·递归
txinyu的博客14 小时前
解析muduo源码之 StringPiece.h
开发语言·网络·c++
浅念-14 小时前
C语言——单链表
c语言·开发语言·数据结构·经验分享·笔记·算法·leetcode
墨雪不会编程14 小时前
C++【string篇4】string结尾篇——字符编码表、乱码的来源及深浅拷贝
android·开发语言·c++