一个成员函数的简单示例

有时我们希望回调某个类里面的函数,而不是静态函数或全局函数。

这时就会用到成员函数,以下是成员函数的使用示例:

(以下代码在VS2010及更高版本使用,VS2010以下的版本没有std::functiont和std::bind,而是另外的定义)

 1 #include <functional>
 2 // 回调函数定义,三个参数
 3 typedef std::function<bool(int,int,std::string&)> CallFunc;    
4
// 说明:func函数名, _Object指针, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3表示回调函数的三个参数,按函数参数数量而定 5 #define FUNC_CALLBACK_1(func, _Object) std::bind(&func,_Object, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
6 class TestClass 7 { 8 public: 9 bool func(int a, int b, std::string & str){ return true; } 10 11 }; 12 13 void main() 14 { 15 // 定义函数变量 16 CallFunc _func; 17 // 创建类 18 TestClass test; 19 // 赋值函数变量,如果未赋值则默认为空,可以判断{ if (_func == 0 || _func._Empty()){ return "函数为空!";} } 20 _func = FUNC_CALLBACK_1(TestClass::func, &test); 21 }

 

posted @ 2013-09-06 13:06  elephant-x  阅读(366)  评论(0编辑  收藏  举报