筆記:C++ 函數對象

內容主要來自維基百科ios

函數對象:一個對象容許被看成普通函數來使用函數

與函數指針比,優勢:spa

1.編譯器能夠內聯執行函數對象的調用指針

2.函數對象內部能夠保持狀態code

 

C++中,function object 是定義了函數調用運算符()的類對象,稱做class type functor對象

C++中,還有其餘類型的function objectblog

 

C++ stl中的algorithm,大量使用函數對象來處理容器中的元素。編譯器

 

使用例子:it

                                            
  //File Name: functor.cpp
  //Created Time: 2017年09月07日 星期四 20時13分30秒
                                   
#include <iostream>
using namespace std;

template<typename T>
struct plus{
    T operator()(const T& x,const T& y) const{
        return x + y;
    }
};
int main(){
    //產生仿函數對象
    plus<int> plusobj;

    //這樣子使用仿函數,就像使用通常函數同樣
    cout << plusobj(3,5) << endl;
    
    //直接產生仿函數的臨時對象(第一對小括號),而且調用它(第2對小括號)
    cout << plus<int>()(3,5) << endl;
    
    return 0;
}
相關文章
相關標籤/搜索