函数指针

1.格式

 /* C */
 void(*fp)(void)=NULL;  // 对应的是 void fun() 类型的函数
 int(*fp)(int)=NULL;    // 对应的是 int fun(int) 类型的函数
/* C++ */
 int(*fp)(int)=NULL;            // 对于静态成员函数(和C一样)
 int(ClassName::*fp)(int)=NULL; //对于普通成员函数要加上类域  

 

2.示例

 

typedef int(*fp)(int);  /** C **/

int f(int a)
{
    cout << a << endl;
    return 1;
}
int main()
{

   fp pf = NULL;
   pf = (fp)*(&f);
   cout << pf(2) << endl;
   return 0;
      
/* 或者不使用typedef
   int(*fp)(int)=NULL;
  pf=f;
   cout<<pf(2)<<endl;
*/
}


/*******************************************************************/
class A /** C++ **/ { public: void fun1(int a){ cout << a << endl; } static void fun2(int b){ cout << b << endl; } }; int main() { A b; void(A::*fp)(int) = NULL; /*对普通成员函数的调用*/ fp = &A::fun1; (b.*fp)(2); // 调用fun1 //-----------------------------+ void(*pf)(int) = NULL; /*对静态成员函数的调用,同C一样*/ pf = b.fun2; pf(4); //调用fun2 return 0; }

 

  

posted @ 2017-03-06 16:22  whlook  阅读(233)  评论(0编辑  收藏  举报