谈谈c++的仿函数(或称函数对象)

  • 缘起:在c++ STL中泛型算法for_each()的使用中提到了仿函数的使用,这里从实例的角度出发,分析c++ 中的仿函数。
  • 定义及使用方式:c++ 仿函数(仿函数不仅在c++ 语言中有,如Java)即为类对象能像函数那样调用使用,因此又称为函数对象。c++中通过在类的定义中重载()运算符实现。
  • 注意:仿函数在使用时与构造函数本质的区别是:构造函数是在声明(定义)类对象的时候调用;而仿函数是定义好的类对象上进行(重载)调用。
  • 使用仿函数的好处:任何事物的出现都有其必要性,那么仿函数出现的好处是:通过仿函数在同一个类中拥有两种不同状态的对象。在实例二中说明。
  • 实例1
#include<iostream>
using namespace std;

template <class T>
class Say {
public:
	void operator()(T a)
	{
		cout << a << endl;
	}
};

template<class T>
void allFunc(int arr[], int len, T func)
{
	for (int i = 0; i < len; i++)
		func(arr[i]);
}

int main()
{
	int arr[5] = {1, 2, 3, 4, 5};
	allFunc<Say<int>>(arr, 5, Say<int>());
	system("pause");
	return 0;
}

上面实例中在main函数的allFunc()函数的调用中,通过Say()构造无名的Say对象,并将其以参数传入allFunc中通过()重载函数以仿函数的方式进行访问。

  • 实例2
#include<iostream>
using namespace std;

template<class T>
class Functor {
public:
	enum Type{plus, sub};
	Functor(Type t = plus) :type(t) {}
	T operator()(T a, T b)
	{
		if (this->type == plus)//type == plus也可,默认是当前对象的type成员
			return a + b;
		else
			return a - b;
	}
public:
	Type type;
};

int main()
{
	Functor<int> plu(Functor<int>::plus);
	Functor<int> su(Functor<int>::sub);

	cout << plu(3, 2) << endl;
	cout << su(3, 2) << endl;
	system("pause");
	return 0;
}

如上面实例2所示,通过在构造函数中传入不同的变量值从而可以构建不同状态(功能)的实例,通过仿函数的形式对实例进行执行不同的功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章