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

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

相关推荐
feng_you_ying_li18 小时前
C++复习二,继承与多态
c++
小小de风呀18 小时前
de风——【从零开始学C++】(十一):list的基本使用和模拟实现
开发语言·c++·list
陌路2018 小时前
C++高级进阶--夯实进阶基础(1)
开发语言·c++
zlinear数据采集卡19 小时前
基准电压电路深度解析:从理论参数到ZLinear采集卡的精准参考实战
c语言·单片机·嵌入式硬件·fpga开发·自动化
日晨难再20 小时前
C语言&Python&Bash&Tcl:全局变量和局部变量
c语言·python·bash·tcl
郝学胜-神的一滴20 小时前
中级OpenGL教程 008:精准控制高光光斑大小与强度
c++·unity·godot·three.js·图形学·opengl·unreal
牢姐与蒯20 小时前
c++数据结构之c++11(一)
数据结构·c++
折戟不必沉沙20 小时前
构造和析构函数能否是虚函数?能否调用虚函数?
c++
-To be number.wan21 小时前
算法日记 | STL- sort排序
c++·算法
不想写代码的星星21 小时前
编译期策略模式:当模板成为策略容器
c++