您的位置:首页 > 编程语言 > C语言/C++

C++函数指针用法

2016-03-10 11:04 281 查看
来源:《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 functions
address : value
001DF97C: 12.3
001DF984: 45.6
--------------------------
using an array of pointers to functions
address : value
001DF97C: 12.3
001DF984: 45.6
001DF98C: 78.9
--------------------------
using a pointer to a pointer to a function
address : value
001DF97C: 12.3
001DF984: 45.6
001DF98C: 78.9
--------------------------
using pointers to an array of pointers
address : value
001DF97C: 12.3
001DF984: 45.6
001DF98C: 78.9
--------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 函数指针