/*
文件内容:指向函数的指针,和其指针数组的使用
日期:2008-02-01
作者:大z
*/
#include <iostream>
using namespace std;
typedef void (*VP)(int); // 定义一个函数指针类型
typedef int (*FP)(int); // 定义一个函数指针类型
int fun(int a) // 定义一个FP类型变量所指对象
{
return a;
}
void t1(int i){ cout << "test1 :" << i << endl; } // 定义VP类型变量所指对象
void t2(int i){ cout << "test2 :" << i << endl; }
void t3(int i){ cout << "test3 :" << i << endl; }
/*
功能:
通过形参接收一个指向函数的指针数组,并通过参数三的参数值向三个函数
参数:
fp: VP类型的数组
fp_length: fp的长度
para: 函数指针所指函数的参数
*/
void print( VP fp[], int fp_length , int para[] )
{
for(int i=0; i<fp_length; i++)
{
fp[i](para[i]);
}
}
int main()
{
int (*p)(int); // 定义一个函数指针
p = fun; // 将函数的地址赋值给函数指针
cout << fun << endl; // 通过函数名直接显示函数的地址
cout << p << endl; // 通过函数指针取得函数的地址
cout << p(20) << endl; // 标准C++写法 -- 通过函数指针调用所指函数
cout << (*p)(30) << endl; // C语言中的写法 -- 通过函数指针调用所指函数
FP fp1; // 定义一个函数指针类型的变量
fp1 = fun; // 将函数的地址赋值给函数指针
cout << fp1 << endl; // 通过函数指针取得函数的地址
VP pa[] = {t1, t2, t3}; // 定义一个函数指针的数组
for(int i=0; i<3; i++)
{
pa[i](i); // 依次调用三个函数
}
cout << pa[0] << endl; // 依次打印函数的地址
cout << pa[1] << endl;
cout << pa[2] << endl;
cout << t1 << endl; // 依次打印函数的地址
cout << t2 << endl;
cout << t3 << endl;
cout << sizeof(pa) << endl; // 指针数组的大小
int para[] = {11,22,33};
print(pa, 3, para); // 调用函数分别显示所指函数
return 0;
}