arfupt.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // arfupt.cpp -- an array of function pointers
  2. #include <iostream>
  3. // various notations, same signatures
  4. const double * f1(const double ar[], int n);
  5. const double * f2(const double [], int);
  6. const double * f3(const double *, int);
  7. int main()
  8. {
  9. using namespace std;
  10. double av[3] = {1112.3, 1542.6, 2227.9};
  11. // pointer to a function
  12. const double *(*p1)(const double *, int) = f1;
  13. auto p2 = f2; // C++0x automatic type deduction
  14. // pre-C++0x can use the following code instead
  15. // const double *(*p2)(const double *, int) = f2;
  16. cout << "Using pointers to functions:\n";
  17. cout << " Address Value\n";
  18. cout << (*p1)(av,3) << ": " << *(*p1)(av,3) << endl;
  19. cout << p2(av,3) << ": " << *p2(av,3) << endl;
  20. // pa an array of pointers
  21. // auto doesn't work with list initialization
  22. const double *(*pa[3])(const double *, int) = {f1,f2,f3};
  23. // but it does work for initializing to a single value
  24. // pb a pointer to first element of pa
  25. auto pb = pa;
  26. // pre-C++0x can use the following code instead
  27. // const double *(**pb)(const double *, int) = pa;
  28. cout << "\nUsing an array of pointers to functions:\n";
  29. cout << " Address Value\n";
  30. for (int i = 0; i < 3; i++)
  31. cout << pa[i](av,3) << ": " << *pa[i](av,3) << endl;
  32. cout << "\nUsing a pointer to a pointer to a function:\n";
  33. cout << " Address Value\n";
  34. for (int i = 0; i < 3; i++)
  35. cout << pb[i](av,3) << ": " << *pb[i](av,3) << endl;
  36. // what about a pointer to an array of function pointers
  37. cout << "\nUsing pointers to an array of pointers:\n";
  38. cout << " Address Value\n";
  39. // easy way to declare pc
  40. auto pc = &pa;
  41. // pre-C++0x can use the following code instead
  42. // const double *(*(*pc)[3])(const double *, int) = &pa;
  43. cout << (*pc)[0](av,3) << ": " << *(*pc)[0](av,3) << endl;
  44. // hard way to declare pd
  45. const double *(*(*pd)[3])(const double *, int) = &pa;
  46. // store return value in pdb
  47. const double * pdb = (*pd)[1](av,3);
  48. cout << pdb << ": " << *pdb << endl;
  49. // alternative notation
  50. cout << (*(*pd)[2])(av,3) << ": " << *(*(*pd)[2])(av,3) << endl;
  51. // cin.get();
  52. return 0;
  53. }
  54. // some rather dull functions
  55. const double * f1(const double * ar, int n)
  56. {
  57. return ar;
  58. }
  59. const double * f2(const double ar[], int n)
  60. {
  61. return ar+1;
  62. }
  63. const double * f3(const double ar[], int n)
  64. {
  65. return ar+2;
  66. }