1. 程式人生 > >c++函式物件建構函式和operator()執行關係

c++函式物件建構函式和operator()執行關係

函式物件常用在stl的演算法中,用於特殊的匹配定製功能。

在執行的函式物件中建構函式和過載()函式的關係先後順序
如下程式碼:
find_if(v.begin(), v.end(), search_num(4))

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

template <typename T>

class search_num
{
    T m_val;
public
: search_num(T value):m_val(value) { cout << " construct " <<value<< endl; } bool operator()(const T val){ cout << "opeatorr()" << endl; return (m_val == val); } }; int main() { vector<int> v; for (int i = 1; i < 6; i++) { v.push_back(i); } vector
<int>
::iterator it = find_if(v.begin(), v.end(), search_num<int>(4)); if (it != v.end()) { cout << " find num " << *it << endl; } else { cout << "not find the num" << endl; } return 0; }

執行結果:

construct 4
opeatorr
() opeatorr() opeatorr() opeatorr() find num 4

結論:
先執行建構函式,在執行過載函式