定義了叫用作業符的類,其對象常稱為函數對象,即它們是行為類似函數的對象。可以為類類型的對象重載函數叫用作業符。一般為表示操作的類重載叫用作業符。函數叫用作業符必須聲明為成員函數。一個類可以定義函數叫用作業符的多個版本,由形參的數目或類型加以區別。
例如,可以定義名為 absInt 的結構,該結構封裝將 int 類型的值轉換為絕對值的操作:
class absInt{public: int operator() (int val) { return val < 0 ? -val : val; }};
貌似什麼的例子沒什麼吸引力, 下面來個例子.
比如我們有個儲存字串的vector<string> words; 我們想計算其中字元數大於6的個數, 我們現在使用標準庫的函數count_if來計算. count_if最後傳入處理函數,函數形式like this:
bool funcName(const string &s) ;
此函數只接受一個參數,並且是count_if來為你傳入, 好,下面我們寫個比較函數:
// determine whether a length of a given word is 6 or more bool GT6(const string &s) { return s.size() >= 6; }
這樣來調用就ok了
vector<string>::size_type wc = count_if(words.begin(), words.end(), GT6);
很明顯這樣有一個最大的缺點就是,6是寫入程式碼, 如果我要大於7的個數呢? 在寫一個? 那大於8的呢?..............
有的傢伙說: 日, 把6定義成一個變數就好了. 那是可以,但是太不優雅了(裝一次逼). 況且如果需要的不是這種簡單的大於6個數的需求呢?
有的傢伙說: 靠你媳婦不戴套, 直接寫比這簡單啊! 我太陽,也是哈, 但是如果是一個比較複雜的演算法,別人就提供了這樣的介面呢?
......
好了,那就函數對象唄, 不然不跑題了, 日.
// determine whether a length of a given word is longer than a stored bound class GT_cls { public: GT_cls(size_t val = 0): bound(val) { } bool operator()(const string &s){ return s.size() >= bound; } private: std::string::size_type bound; };
調用方式:
//大於6個cout << count_if(words.begin(), words.end(), GT_cls(6)) << " words 6 characters or longer" << endl;//大於5個cout << count_if(words.begin(), words.end(), GT_cls(5)) << " words 5 characters or longer" << endl;//迴圈體for (size_t i = 0; i != 11; ++i) cout << count_if(words.begin(), words.end(), GT(i))<< " words " << i << " characters or longer" << endl;