c++传递函数参数

传递普通函数和类的成员函数方式不同,原因是传递函数参数实际传的是函数的地址,但是普通函数和成员函数的地址获取方式不太相同。普通函数只要传递一个函数名称即可,但是成员函数在类的内部中没有地址,选择一个成员函数就意味着得知道该函数在类中的偏移量,因此需要知道该对象和对应的偏移量,才能得到真实的地址。当然,你也可以将成员函数设置为静态函数(static)来当作普通函数来看待。

由于处理方式不同,所以可以采用函数重载的方式。由于每次传的对象类型可能不同,所以采用template。

代码如下:

 1 #include<iostream>;
 2 using namespace std;
 3 class ABC {
 4     public:
 5         void f1(int n, int b);
 6         void f2(int n);
 7 };
 8 
 9 void ABC::f1(int n, int b) {
10     cout << n << "," << b << endl;
11 }
12 
13 void ABC::f2(int n) {
14     cout << "member function:" << n << endl;
15 }
16 
17 void f(int n) {
18      cout << "normal function: " << n << endl;
19 }
20 // normal function
21 void cb(void(*callback)(int), int n) {
22      callback(n);
23 }
24 // member function
25 template <class T>
26 void cb(T *obj, void (T::*callback)(int), int n) {
27      (obj->*callback)(n);
28 }
29 int main(void) {
30     ABC *abc = new ABC();
31     abc->f1(1, 2);
32     abc->f2(3);
33     // invoke member function
34     cb(abc, &ABC::f2, 4);
35     // invoke normal function
36     cb(f, 5);
37     
38     system("pause");
39     return 0;
40 }
posted @ 2012-09-13 14:45  bilipan  阅读(2462)  评论(0编辑  收藏  举报