C++函数指针简介及应用

C/C++中函数指针是一种指针类型,其指向一个函数的首地址。既然是指针类型,使用时就应该像int,int*等类型一样申明定义。

如语句 int (*fp) (int, int); 就是声明一个函数指针变量fp,其指向一个输入为两个int型参数,输出为int型的函数。

对函数指针变量赋值可以有两种方式。如有一个函数 int Add(int a, int b){return a+b;}。则可以定义:

1) fp=&Add;

2) fp=Add;

前一种方式是显式赋值,后一种是隐式赋值。两者是等同的。同样在使用函数指针变量时也有两种方式:

1)(*fp)(2,3);

2)fp(2,3);

两者均相当于与执行Add(2,3),结果为5。

函数指针主要可以用于两个场景中:菜单设计和函数参数。菜单设计中我们可以使用一个函数指针数组来表示几种操作。另外函数指针变量也可以作为函数参数,C++中的endl操作符就是一个很好的例子,可以参考http://www.cnblogs.com/ldeng/archive/2012/09/02/2667942.html

 

下面是一个完整的函数指针使用例子。其中包括函数指针的两种定义方式和两种使用方法。另外,display函数是函数指针作为函数参数的应用。简易计算器体现了函数指针在菜单设计中的应用。

 1 #include<iostream>
 2 using namespace std;
 3 
 4 
 5 int Add(int a, int b)
 6 {
 7     return a+b;
 8 }
 9 
10 int Sub(int a, int b)
11 {
12     return a-b;
13 }
14 
15 int Mul(int a, int b)
16 {
17     return a*b;
18 }
19 
20 int Div(int a, int b)
21 {
22     if(b==0)
23     {
24         cout<<"Error!"<<endl;
25         exit(-1);
26     }
27     else
28         return a/b;
29 }
30 
31 
32 void Display()
33 {
34     cout<<"Function pointer can be a function parameter"<<endl;
35 }
36 
37 void Test(void (*fp)())
38 {
39     fp();
40 }
41 
42 
43 
44 int main()
45 {
46     int (*intfp)(int,int)=&Add;  //explict
47     int (*intfp2)(int,int)=Add;  //implict
48     cout<<intfp<<endl;   
49     cout<<intfp2<<endl;
50     cout<<intfp(2,3)<<endl;  //implict
51     cout<<(*intfp)(2,3)<<endl; //explict
52 
53     Test(Display); //display is a funtion parameter
54 
55     while(1)
56     {
57         int (*ope[4])(int a, int b)={Add,Sub,Mul,Div};  //here ope[] is an array, and each element is a function pointer.
59         int a,b;
60         int sel;
61         cout<<"Please input two integers: ";
62         cin>>a;
63         cin>>b;
64         cout<<"Please select the operation: "<<endl;
65         cout<<"1: +"<<endl;
66         cout<<"2: -"<<endl;
67         cout<<"3: *"<<endl;
68         cout<<"4: /"<<endl;
69         cout<<"0: End"<<endl;
70         cin>>sel;
71         if(sel<0 || sel>4)
72             cout<<"Error operation!"<<endl;
73         else if(sel==0)
74             break;
75         else
76         {
77             int result=ope[sel-1](a,b);
78             cout<<"The result is: "<<result<<endl;
79         }
80     }
81     return 0;
82 }

 

 

posted @ 2012-09-02 23:40  ldeng  阅读(1889)  评论(8编辑  收藏  举报