日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
淺談C++函數(shù)對象

一個(gè)函數(shù)對象,即一個(gè)重載了括號操作符“()”的對象。當(dāng)用該對象調(diào)用此操作符時(shí),其表現(xiàn)形式如同普通函數(shù)調(diào)用一般,因此取名叫函數(shù)對象。

(一)函數(shù)對象

在來回顧一下什么是函數(shù)對象,就是一個(gè)重載'()’運(yùn)算符的類的對象。這樣就可以直接使用‘對象名()’的方式,這跟調(diào)用函數(shù)一樣,所以稱謂函數(shù)對象??磦€(gè)例子:

\#include  
\#include  

class Printer{
public:
 explicit Printer(){};
 void operator()(const std::string & str)const{
   std::coutprint;
 print("hello world!");
 return 0;
}

現(xiàn)在來說說函數(shù)對象有哪些好處:

(1)函數(shù)對象有自己的狀態(tài),即它可以攜帶自己的成員函數(shù),而且這個(gè)函數(shù)對象在多次調(diào)用的過程中它的那些狀態(tài)是共享的,而函數(shù)則不能做到這點(diǎn)(除非定義函數(shù)內(nèi)部的靜態(tài)變量或者全局變量)。

(2)函數(shù)對象有自己的類型,而普通函數(shù)則沒有。在使用STL的容器時(shí)可以將函數(shù)對象的類型傳遞給容器作為參數(shù)來實(shí)例化相應(yīng)的模板,從而來定制自己的算法,如排序算法。

假設(shè)我需要一個(gè)數(shù)字產(chǎn)生器,我給定一個(gè)初始的數(shù)字,然后每次調(diào)用它都會給出下一個(gè)數(shù)字。

\#include  
\#include  
\#include  
\#include  

class SuccessiveNumGen
{
public:
 SuccessiveNumGen(int origin = 0):m_origin(origin){}
 int operator()(){
   return m_origin++;
 }
private:
 int m_origin;
};

int main(int argc,char * argv[]){
 std::vector
  
    dest;  generate_n(back_inserter(dest),10,SuccessiveNumGen(3));  
   for(int i=0;ireturn 0; } 
  

注:此處用到了STL的算法,generate_n會調(diào)用SuccessiveNumGen函數(shù)十次,back_inserter會將SuccessiveNumGen函數(shù)的返回值插入到dest中。

(二)Boost.Thread中函數(shù)對象的使用

\#include  
\#include  
\#include  

void wait(int sec){
 boost::this_thread::sleep(boost::posix_time::seconds(sec));
}

boost::mutex mutex;

class SayHello{
public:
 explicit SayHello(const std::string & name,int times)
   :_name(name),_times(times){}
 void operator()()const{
   for(int i=0;i<_times class="hljs-built_in" style="color: #0086b3;line-height: 26px">wait(1);
     boost::lock_guard<:mutex> lock(mutex);
     std::cout" says hello ("")""Lux",5);
 SayHello jax("Jax",5);
 
 boost::thread thr1(lux);
 boost::thread thr2(jax);
 
 thr1.join();
 thr2.join();
 return 0;
}

  
  

img


文章名稱:淺談C++函數(shù)對象
文章路徑:http://www.5511xx.com/article/djcoioe.html