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

結論:
先執行構造函數,在執行重載函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章