[c++学习笔记24]: STL- 函数对象(仿函数)

函数对象(仿函数)

1 函数对象概念

概念:

  • 重载函数调用操作符的类,其对象常称为函数对象
  • 函数对象使用重载的()时,行为类似函数调用,也叫仿函数

本质:

函数对象(仿函数)是一个,不是一个函数

2 函数对象使用

特点:

  • 函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
  • 函数对象超出普通函数的概念,函数对象可以有自己的状态
  • 函数对象可以作为参数传递
#include<iostream>
using namespace std;
#include<string>
class MyAdd
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};//1、函数对象在使用时,可以像普通函数那样调用, 可以有参数,可以有返回值
void test01() {
	MyAdd myadd;
	int c= myadd(10, 20);
	cout << c << endl;
}

//2、函数对象可以有自己的状态
class Myprint
{
public:
	Myprint()
	{
		count = 0;
	}
	void operator()(string test)
	{
		cout << test << endl;
		count++;
	}
	int count;
};
void test02() {
	Myprint myprint;
	myprint("hello c++");
	myprint("hello c++");
	myprint("hello c++");
	myprint("hello c++");
	cout << "myprint调用次数为:" << myprint.count << endl;
}
//3、函数对象可以作为参数传递
void doMyprint(Myprint &myy,string test)
{
	myy(test);
}
void test03() {
	Myprint mmm;
	doMyprint(mmm, "开学啦啦啦啦");
}
int main()
{
	test01();
	cout << "--------------------------" << endl;
	test02();
	cout << "--------------------------" << endl;
	test03();
	system("pause");
	return 0;
}

总结:

  • 仿函数写法非常灵活,可以作为参数进行传递。

在这里插入图片描述

打个小广告,欢迎关注我的公众号“麦香E站”,分享人工智能,信通学习,数学提高,外语学习,生活理财等多方面知识以及我多年积累的学习资源分享~
公众号后台回复 “编程” 获取我多年来积攒的海量编程电子书~
后台回复“latex”获取我倾力所作latex快速入门手册~
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值