C++11function函数用法

来源:互联网 发布:python进程和线程 编辑:程序博客网 时间:2024/06/06 02:26

废话不多说,直接看代码

#include <iostream>
#include <windows.h>
#include <functional>

using namespace std;
typedef function< void() >CallFunc_1; //无参空返回类型
typedef function< int ( bool ) >CallFunc_2; //带参非空返回类型

class A
{
public:
 void Init( CallFunc_1 callFunc1, CallFunc_2 callFunc2 )
 {
  callFunc1();
  callFunc2( true );
 }
};

void globalCallback_1(  )
{
 cout << "回调了globalCallback_1无参空返回类型全局函数" <<endl;
}

int globalCallback_2( bool bTmp )
{
 cout<< "回调了globalCallback_2带参非空返回类型全局函数" <<endl;
 return 0;
}

class B
{
public:
 void Init()
 {
  A a;
  //传类里面的函数,如果带一个参需加placeholders::_1,如果带两个参则placeholders::_2, 三个则placeholders::_3......以此类推,如果不带参就不加placeholders::...
  a.Init( bind( &B::callback_1_byB, this ), bind( &B::callback_2_byB, this, placeholders::_1 ) );
  a.Init( globalCallback_1, globalCallback_2 ); //传全局里面的函数
 }
 void callback_1_byB()
 {
  cout << "回调了B类里面的callback_1_byB函数 " <<endl;
 }
 int callback_2_byB( bool bFinish )
 {
  if( bFinish )
  {
   cout << "回调传入'true'值 " <<endl;
  }
  cout << "回调了B类里面的callback_2_byB函数 " <<endl;
  return 0;
 }
};

void main()
{
 B b;
 b.Init();
 system( "pause" );

}

1 0
原创粉丝点击