C++函数与指针


当前第2页 返回上一页

代码:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

//arfupt.cpp -- an array of function pointers

#include<iostream>

//various notations,same signatures

const double *f1(const double ar[],int n);

const double *f2(const double [],int);

const double *f3(const double *,int);

 

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 utomatic  type deduction

    //pre-C++11 can use the following code instead

    //const double *(*p2)(const double *,int) = f2;

    cout<<"Using pointers to functions:\n";

    cout<<"Address Value\n";

    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};

    //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<<"\nUsing an array of pointers to functions:\n";

    cout<<"Address Value\n";

    for(int i = 0;i < 3; i++)

        cout<<pa[i](av,3)<<":"<<*pa[i](av,3)<<endl;

    cout<<"\nUsing a pointer to a pointer to a function:\n";

    cout<<"Address Value\n";

    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<<"\nUsing pointers to an array of pointers:\n";

    cout<<"Address Value\n";

    //easy way to declare pc

    auto pc = &pa;

    // pre-C++11 can use the following code instead

    // const double *(*(*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;

}

 

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;

}

以上就是C++函数与指针的详细内容!

返回前面的内容

相关阅读 >>

在不同函数中可以使用相同名字的变量吗

c语言定义函数

c语言中有且唯一的函数是什么函数

c语言求平方函数是什么

c语言指针用法有哪些

用c语言指针如何求最大值最小值

c语言中将一个字符串转换到整型数据类型的函数是什么?

c语言sqrt函数的用法

c语言中文本输出的函数名称是什么?

malloc函数的用法

更多相关阅读请进入《指针》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...