C 學習筆記6 函式物件

2021-10-11 02:33:56 字數 907 閱讀 3195

對於乙個運算子函式來說,它或者是類的成員,或者至少含有乙個類型別的引數。

//錯誤: 不能為int重定義內建的運算子

int operator+(int, int);

sort(words.begin(), words.end(), (const string &a, const string &b));

class shorterstring

};//shorterstring定義了函式運算子(), 使得shorterstring可以想函式一樣呼叫

//我們可以用這個類替代lambda表示式

sort(words.begin(), words.end(), shorterstring());

//表示lambda及相應捕獲行為的類

class sizecomp //該形參對應捕獲的變數

//該呼叫運算子的返回型別,形參和函式體都與lambda一致

bool operator()(const string &s) const

};find_if(words.begin(), words.end(), sizecomp(sz));

// 普通函式

int add(int i, int j)

//lambda 其產生乙個未命名的函式物件類

auto mod = (int i, int j) ;

//函式物件類

struct divide

};#include functionf1 = add;

functionf2 = divide();

functionf3 = (int i, int j) ;

cout

C 函式物件學習筆記

c 似乎越來越希望和c撇清關係,在支援c的各種特性的前提下,又有一些獨有的對c的語法實現。函式物件很大程度上和函式指標作用類似,c裡有函式指標,相應c 有函式物件,當然,在c 情況下,函式物件肯定略顯強大一些。有了函式物件,感覺就算是邁出了函式式程式設計的第一步了。只需要過載 就可以了,乙個例項 i...

C 學習筆記 (函式物件(仿函式))

先考慮乙個簡單的例子 假設有乙個vector,你的任務是統計長度小於5的string的個數,如果使用count if函式的話,你的 可能長成這樣 bool lengthislessthanfive const string str int res count if vec.begin vec.end...

ES6學習筆記(五) 函式與物件

function log x,y world log hello hello world log hello china hello china log hello hellofunction foo foo undefined,5 foo 1,5 foo 1,2 foo typeerror can...