C++函数指针用法

来源:互联网 发布:百会软件 编辑:程序博客网 时间:2024/04/30 16:16

来源:《C++ Primer Plus》(第六版)(中文版)(第7章第10节函数指针)

1、代码:

#include <iostream>//三个函数,分别返回一个数组的三个地址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;}int main(){using namespace std;double av[3] = { 12.3, 45.6, 78.9 };cout << "--------------------------" << endl;cout << "using pointers to functions" << endl;const double *(*p1)(const double *, int) = f1;auto p2 = f2;//or const double *(*p2)(const double *, int) = f2;cout << "address : value" << endl;cout << (*p1)(av, 3) << ": " << *(*p1)(av, 3) << endl;cout << p2(av, 3) << ": " << *p2(av, 3) << endl;cout << "--------------------------" << endl;cout << "using an array of pointers to functions" << endl;const double *(*pa[3])(const double*, int) = { f1, f2, f3 };cout << "address : value" << endl;for (int i = 0; i != 3; i++){cout << pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;}cout << "--------------------------" << endl;cout << "using a pointer to a pointer to a function" << endl;auto pb = pa;//or const double *(**pb)(const double*, int) = pa;cout << "address : value" << endl;for (int i = 0; i != 3; i++){cout << pb[i](av, 3) << ": " << *pb[i](av, 3) << endl;}cout << "--------------------------" << endl;cout << "using pointers to an array of pointers" << endl;auto pc = &pa;//or const double *(*(*pc)[3])(const double *, int) = &pa;const double *pcs = (*pc)[1](av, 3);cout << "address : value" << endl;cout << (*pc)[0](av, 3) << ": " << *(*pc)[0](av, 3) << endl;cout << pcs << ": " << *pcs << endl;cout << (*(*pc)[2])(av, 3) << ": " << *(*(*pc)[2])(av, 3) << endl;cout << "--------------------------" << endl;return 0;}
2、测试结果:

--------------------------using pointers to functionsaddress : value001DF97C: 12.3001DF984: 45.6--------------------------using an array of pointers to functionsaddress : value001DF97C: 12.3001DF984: 45.6001DF98C: 78.9--------------------------using a pointer to a pointer to a functionaddress : value001DF97C: 12.3001DF984: 45.6001DF98C: 78.9--------------------------using pointers to an array of pointersaddress : value001DF97C: 12.3001DF984: 45.6001DF98C: 78.9--------------------------

0 0
原创粉丝点击