7.3.3 通过函数指针将函数作为另一个函数的参数
函数指针的一个功用是把函数地址作为参数传送,以提高函数的通用性和灵活性,如代码7.10所示。
代码7.10 函数指针作参数PointerToFuncSample
<————————————文件名:example710.cpp———————————————> 01 #include<iostream> 02 typedef void(*hs)(int);//typedef用法,hs可以当成类型来用,声明函数指针 03 using namespace std; 04 05 void Just_Print(int i)//函数定义,输出参数i 06 { 07 cout<<i<<""; 08 } 09 void Call(const char*name,hs func)//Call函数定义,函数指针func作为参数 10 { 11 int array[9]={1,2,3,4,5,6,7,8,9}; 12 cout<<name<<endl; 13 for(int i=0;i<9;i++) 14 func(array[i]);//通过函数指针调用函数 15 } 16 int main() 17 { 18 char name[]="输出";//字符数组name 19 hs pFun=Just_Print;//声明一个hs型函数指针,并用Just_Print为其初始化 20 Call(name,pFun);//调用Call()函数,其内部调用pFun,即Just_Print()函数 21 cout<<endl; 22 return 0; 23 }
输出结果如下所示。
输出 1 2 3 4 5 6 7 8 9
【代码解析】代码第2行,“typedef void(hs)(int);”将指向“一个int型参数,无返回值的函数”的指针用别名hs代替,这样,可在程序中声明hs型的函数指针。函数call的形式为“void Call(const charname,hs func)”,第一个参数是字符串,第二个参数是hs型的函数指针,在Call函数内通过该函数指针参数调用该指针所指向的函数Just_Print(),这样,Just_Print()函数的地址作为实参传递给Call()函数中的形参func。从本质上讲,这属于传指针调用。