STL函数对象:与函数指针的比较

一、函数对象、函数指针的定义和使用

      二者定义方式不同,使用方式相同。

#include 
using namespace std;

//function object
class obj_Add
{
public:
	int operator() (int val1, int val2)
	{
		return val1 + val2;
	}
};

//function pointer
int fun_Add(int val1, int val2)
{
	return val1 + val2;
}


int main(int argc, char *argv[])
{
	//function object
	obj_Add obj_add;
	cout<
二、函数对象、函数指针的区别

2.1 函数对象内可以携带附加数据,函数指针不行

      见博客《STL函数对象:定义、及其在STL中的应用》中的2.2节。

      http://blog.csdn.net/guowenyan001/article/details/10017799

2.2 函数对象可以用来封装类成员函数指针

#include 
using namespace std;

//function object
template 
class fun_Obj
{
public:
	fun_Obj(void (T::*f)(char *), T* t)
		: pFunc(f), m_t(t) { }

public:
	void operator() (char* name)
	{
		(m_t->*pFunc)(name);
	}

private:
	void (T::*pFunc)(char *);
	T* m_t;
};

//
class output_Obj
{
public:
	void output(char* name)
	{
		cout<<"Hello "< fun_obj(&output_Obj::output, &output_obj);
	fun_obj("world.");


	return 1;
};

三、让一个函数既接受函数指针,又接受函数对象,最简单的方法就是使用模板。

#include 
using namespace std;

//function object
class great
{
public:
	great(int val) : m_val(val) { }

public:
	bool operator() (int val)
	{
		return val > m_val;
	}

private:
	int m_val;
};

//function pointer
bool great10(int val)
{
	return val > 10;
}

//function
template 
int count_n(int* arr, int n, FUNC func)
{
	int count = 0;
	for(int i=0; i



你可能感兴趣的:(C/C++/STL)