函數對象
c++中函數名后的()稱為函數調用運算符。函數調用運算符也可以重載,如果某個類重載了函數調用運算符,則該類的實例就是一個函數對象。函數對象本身并不是很有用,但他們使得算法操作的參數化策略成為可能,使通用性算法變得更加通用(讓函數作為參數還可以通過函數指針)實例
class Add{ double Operator()(double x,double y) { return x+y; }};Add plus; //plus就是一個函數對象cout<<plus(1.2,3.4)<<endl;//通過函數對象調用重載函數cout<<Add() ()(1.2,3.4)<<endl; //Add()會創建一個臨時對象學習代碼
#include <iostream>#include <vector>#include <list>#include <algorithm>using namespace std;/*class absInt {};*/ //class和struct都是定義類,struct成員默認屬性為publicvoid PRint(double i){ cout << i << " ";}void myforeach(vector<double>::iterator & t1, vector<double>::iterator & t2, void(*fun)(double i))//可以通過函數指針將一個函數作為另一個函數的參數{ while (t1 != t2) { fun(*t1); ++t1; }}struct absInt { //重載操作符() int operator()(int val) { return val < 0 ? -val : val; }};template <typename elementType>void FuncDisplayElement(const elementType & element){ cout << element << " " ;}template <typename elementType>struct DisplayElement { //存儲狀態 int m_nCount; DisplayElement() { m_nCount = 0; } void operator()(const elementType & element) { ++m_nCount; cout << element << " "; }};int main(){ absInt absObj;//函數對象 int i = -2; unsigned int ui = absObj(i);//通過函數對象調用函數 cout << ui << endl; vector<int> a; for (int i = 0; i < 10; i++) { a.push_back(i); } DisplayElement<int> mResult; mResult = for_each(a.begin(), a.end(), mResult);//把函數對象作為參數傳遞給另一個函數 cout << endl; cout << "數量" << mResult.m_nCount << endl; list<char> b; for (char c = 'a'; c < 'k'; ++c) { b.push_back(c); } for_each(b.begin(), b.end(), DisplayElement<char>());//DisplayElement<char>()會創建一個臨時對象 cout << endl; vector<double> vec = { 76,92,86,74,95 }; cout << "vec里的類容為:" << endl; for_each(vec.begin(), vec.end(), print); cout << "vec里的內容為" << endl; myforeach(vec.begin(), vec.end(), print); getchar(); return 0;}新聞熱點
疑難解答
圖片精選