C++函数对象(仿函数)

函数对象

概念:
1、重载函数调用操作符的类,其对象常称为函数对象
2、函数对象使用重载的()时,行为类似函数调用,也叫仿函数
本质
函数对象(仿函数)是一个,不是一个函数

函数对象的使用

特点:
1、函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
2、函数对象超出普通函数概念,函数对象可以有自己的状态
3、函数对象可以作为参数传递

#include <iostream>
#include <string>
using namespace std;
class Myadd//函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
{
public:
	int operator()(int v1, int v2) {
		return v1 + v2;
	}
};
class Myprint//函数对象超出普通函数概念,函数对象可以有自己的状态
{
public:
	Myprint(){
		this->count = 0;
	}
	void operator()(string test) {
		cout << test << endl;
		this->count++;
	}
	int count;//内部自己的状态
};
void doPrint(Myprint& mp, string test)//函数对象可以作为参数传递
{
	mp(test);
}
void test1()
{
	Myadd myadd;
	cout << "myadd(10,10)=" << myadd(10, 10) << endl;

	Myprint myprint;
	myprint("Hello word");
	myprint("Hello word");
	cout << "myPrint调用次数为:" << myprint.count << endl;

	doPrint(myprint, "Hello C++");

}
int main(void)
{
	test1();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值