生活随笔
收集整理的這篇文章主要介紹了
C++之仿函数简介
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述
仿函數(Functor)又稱為函數對象(Function Object),函數對象是一個對象,但是使用的形式看起來像函數調用,實際上也執行了函數調用,因而得名。仿函數的語法普通的函數調用一樣,調用仿函數,實際上就是通過類對象調用重載后的operator()運算符。所以作為仿函數的類,必須重載operator()運算符。
仿函數的作用:
- 可替代函數指針,使用更加靈活
- 可存儲狀態,形成一種類似于閉包的機制
#include <iostream>using namespace std;#if 0
class Calculation{public:Calculation(int num):m_nCount(num){}void operator()(int n){m_nCount += n;cout<< "m_nCount = " << m_nCount << endl;}
private:int m_nCount;
};void fun(Calculation & cal){cal(5);cal(5);
}int main()
{Calculation cal(3);
// cal(5);
// cal(5);
// fun(cal);fun(Calculation(5));return 0;
}#elseint CallFunc(int *start, int *end, bool (*pf)(int))
{int count=0;for(int *i=start;i!=end+1;i++){count = pf(*i) ? count+(*i) : count;}return count;
}bool Judge(int num)
{return num%2 ? false : true;
}int main()
{int a[10] = {1,2,3,4,5,6,7,8,9,10};int result = CallFunc(a,a+10,Judge);cout<<result<<endl;return 0;
}//class IsGreaterThanThresholdFunctor
//{
//public:
// explicit IsLessThanTenFunctor(int tmp_threshold) : threshold(tmp_threshold){}
// bool operator() (int num) const
// {
// return num>threshold ? true : false;
// }
//private:
// const int threshold;
//};//int RecallFunc(int *start, int *end, IsGreaterThanThresholdFunctor myFunctor)
//{
// int count=0;
// for(int *i=start;i!=end+1;i++)
// {
// count = myFunctor(*i) ? count+1 : count;
// }
// return count;
//}
//int main()
//{
// int a[5] = {10,100,11,5,19};
// int result = RecallFunc(a,a+4,IsLessThanTenFunctor(10));
// cout<<result<<endl;
// return 0;
//}#endif
https://blog.csdn.net/K346K346/article/details/82818801
http://c.biancheng.net/view/354.html
https://blog.csdn.net/qq_35976351/article/details/84103205
https://blog.csdn.net/lms1008611/article/details/81461619
https://blog.csdn.net/whahu1989/article/details/83833138
總結
以上是生活随笔為你收集整理的C++之仿函数简介的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。