首页 > 其他 > 详细

函数指针

时间:2017-03-06 16:28:56      阅读:172      评论:0      收藏:0      [点我收藏+]

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;
}

  

函数指针

原文:http://www.cnblogs.com/whlook/p/6510516.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!