标签:
在看APUE Figure1.10的时候发现signal(SIGINT, sig_int)这里的sig_int直接用的函数名,但是看Thinking-in-C++ Vol.2的时候发现mem_fun(&Shape::draw)却对函数名进行了取地址操作,感觉有疑问就查了一下资料,下面的代码可以展示出这两者之间的一些区别
参考资料:
http://stackoverflow.com/questions/3050805/pointer-to-const-member-function-typedef
http://www.cplusplus.com/reference/functional/mem_fun1_t/
http://www.cnblogs.com/taobataoma/archive/2007/08/30/875743.html
http://www.cplusplus.com/reference/functional/mem_fun/
代码:
1 #include <functional> 2 #include <iostream> 3 #include <algorithm> 4 5 6 using namespace std; 7 8 void my(int arg); 9 10 class MyClass 11 { 12 public: 13 void my(int arg) { cout << arg << endl; } 14 }; 15 16 // 方法1,2 17 18 typedef void func_ptr(int); // func_ptr与func_ptr2本质是一样的,选择哪种定义方式看你的喜好 19 typedef void (*func_ptr2)(int); // 参考:http://www.cnblogs.com/qrlozte/p/4439002.html 20 void dosomething_one(func_ptr ptr); 21 void dosomething_two(func_ptr2 ptr); 22 23 // 方法3,4,5 24 25 void dosomething_three(void (MyClass::*my_ptr)(int)); 26 27 typedef void FuncType(int); 28 typedef FuncType MyClass::*MyClassFuncType; 29 30 typedef void (MyClass::*MemberFuncType)(int); 31 32 void dosomething_four(MyClassFuncType ptr); 33 34 void dosomething_five(MemberFuncType ptr); 35 36 37 38 int main() { 39 /* 40 方法1,2本质是一样的 41 方法3,4,5本质也是一样的 42 */ 43 dosomething_one(my); 44 dosomething_two(my); 45 dosomething_three(&MyClass::my); 46 dosomething_four(&MyClass::my); 47 dosomething_five(&MyClass::my); 48 return 0; 49 } ///:~ 50 51 void my(int arg) 52 { 53 cout << arg << endl; 54 } 55 56 57 void dosomething_one(func_ptr ptr) 58 { 59 ptr(1); 60 } 61 62 void dosomething_two(func_ptr ptr) 63 { 64 ptr(2); 65 } 66 67 void dosomething_three(void (MyClass::*my_ptr)(int)) 68 { 69 MyClass *obj = new MyClass; 70 (obj->*my_ptr)(3); 71 delete obj; 72 } 73 74 void dosomething_four(MyClassFuncType ptr) 75 { 76 MyClass *obj = new MyClass; 77 (obj->*ptr)(4); 78 delete obj; 79 } 80 81 void dosomething_five(MemberFuncType ptr) 82 { 83 MyClass *obj = new MyClass; 84 (obj->*ptr)(5); 85 delete obj; 86 }
C Pointer-to-Function 与 C++ Pointer-to-MemberFunction 的区别
标签:
原文地址:http://www.cnblogs.com/qrlozte/p/4453786.html