- 緣起:在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所示,通過在構造函數中傳入不同的變量值從而可以構建不同狀態(功能)的實例,通過仿函數的形式對實例進行執行不同的功能。