/********************************************************************** * 版权所有 (C)2017, Wang maochun。 * * 文件名称:arfupt.c * 文件标识:无 * 内容摘要:该程序参考C++primer plus,主要熟悉函数指针的使用 * 其它说明:[] ()的优先级比*高 * 当前版本:V1.0 * 作 者:Wang maochun * 完成日期:2017.7.24 * **********************************************************************/ #include <iostream> //various notations ,same signature const double *f1(const double *ar,int n); const double *f2(const double ar[],int n); const double *f3(const double ar[],int n); int main() { using namespace std; double av[3] = {1112.3,1542.6,2227.9}; //pointer to a function const double *(*p1)(const double *,int) = f1; auto p2 = f2; //C++11 automatic type deduction //pre-C++ can use the following code instead //const double *(*p2) (const double *,int) =f2; cout << "Using pointers to functions: "; cout << "Adress Value "; cout << (*p1)(av,3) << ":" << *(*p1)(av,3) <<endl; cout << p2(av,3) << ":" << *p2(av,3) <<endl; //pa an array of pointers //auto doesn't work with list initialization const double *(*pa[3])(const double *,int) = {f1,f2,f3}; //but it does work for initializing to a single value //pb a pointer to first element of pa auto pb = pa; //pre C++11 can use the following code instead //const double *(**pb)(const double *,int) = pa; cout <<" Using an array of pointers to function: "; cout << "Address Value "; for (int i = 0; i<3;i++) cout << pa[i](av,3) <<":" << *pa[i](av,3)<<endl; cout <<" Using a pointer to a pointer to a function: "; cout << "Adress Value "; for (int i = 0; i<3;i++) cout << pb[i](av,3) <<":" << *pb[i](av,3)<<endl; //what about a pointer to an array of function pointers cout << " Using pointers to an array of pointers: "; cout << "Adress Value "; //easy pc =&pa; auto pc = &pa; //pre-C++ can use the following code instead //const doubel *(*(*pc)[3])(const double *,int) = &pa; cout << (*pc)[0](av,3) << ":" <<*(*pc)[0](av,3) <<endl; //hard way to declare pd const double *(*(*pd)[3])(const double *,int ) =&pa; //store return value in pdb const double * pdb = (*pd)[1](av,3); cout << pdb <<":"<< *pdb <<endl; //alternative notation cout << (*(*pd)[2])(av,3) <<":"<< *(*(*pd)[2])(av,3)<<endl; //cin.get(); return 0; } //some rather dull functions const double *f1(const double *ar,int n) { return ar; } const double *f2(const double ar[],int n) { return ar+1; } const double *f3(const double ar[],int n) { return ar+2; }
运行结果:
小技巧:如何定义该函数指针变量? 将函数声明中的函数名通过*p替代
[] ()优先级比*高
该程序每隔几天多读读,简直是指针与函数结合最难的。
Dev C++ 支持C++11 :先在dev的【工具】里找到【编译选项】,在这个【编译时加入以下命令】处打钩,然后在空白栏输入【-std=c++11】,确定.然后就能支持c++11