函数回调和仿函数

函数回调

首先我们得了解函数指针。函数指针是一个指向函数的指针,函数指针可以像一般的函数一样,用于调用函数,传递参数。

函数指针定义方式位

函数返回类型(*指针变量名)(函数参数列表)

int(*func)(int ,int);

这就是一个名为func的函数指针。

 下面写一个例子

#include <iostream>
using namespace std;

int max(int a, int b) {
	return (a > b) ? a : b;
}
int main(void) {

	int(*func)(int ,int);
	func = max;
	cout << func(3, 5) << endl;
	system("pause");
	return 0;
}

我们定义了一个返回类型为int 的函数指针指向函数max(函数指针在写的时候返回值和参数列表都要和需要指向的函数一致)。

赋值时函数max不带括号,也不带参数。由于函数名 Func 代表函数的首地址,因此经过赋值以后,指针变量 func就指向函数max() 代码的首地址了。

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

回调函数就是允许用户把需要调用的方法的指针作为参数传递给一个函数,以便该函数在处理相似事件的时候可以灵活的使用不同的方法。

仿函数

尽管函数指针被广泛应用于实现函数回调,但是C++提供了一个重要的实现回调函数的功能,俺就是函数对象,functor翻译为函数对象,伪函数,他是重载了“()”操作符的普通类对象,从语法上来讲,它与普通函数行为类似 

在STL中广泛应用

// demo 15-36

#include <set>
#include <iostream>
#include <functional>
#include <algorithm>

using namespace std;

class student {
public:
	student(int age) {
		this->age = age;
	}

	bool operator < (const student &right) const{
		return this->age > right.age;
	}

	int getAge() const { return age; }

private:
	int age;
	string name;

};

class FunStudent{
public:
	bool operator () (const student &left, const student &right){
		cout<<"调用了 FunStudent ."<<endl;
		ret  = left.getAge() < right.getAge();
		return ret;
	}

public:
	int ret;
};

int main(void) {
	
	//less 函数对象实现比较,为排序提供依据
	//less 和greater 都是函数对象,有叫仿函数
	//set<int,less<int>> set1;

	set<int,greater<int>> set1;

	for(int i=5; i>0; i--){
		set1.insert(i);
	}
	//less<student>
	set<student, FunStudent>   setStu;  //等同于 set<student,less<student>>
	student  lixiaohua(18);
	student  wangdachui(19);

	//函数对象(仿函数)可以像函数一样直接调用
	FunStudent   funStu;
	 funStu(lixiaohua, wangdachui);
	cout<<"比较结果:"<<funStu.ret<<endl;

	setStu.insert(lixiaohua);
	setStu.insert(wangdachui);

	for (set<student, FunStudent>::iterator it = setStu.begin(); it != setStu.end(); it++) {
		cout << it->getAge() ;
		cout << " ";
	}

	system("pause");
	return 0;
}

 在set中less<>和greater<>就是仿函数。下面列举这两个的简易实现原理。


struct greater
{
bool operator() (const int& iLeft, const int& iRight)
{
       return (iLeft>iRight);   
}
}

struct less
{
bool operator() (const int& iLeft, const int& iRight)
{
       return (iLeft<iRight);    
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值