arfupt1.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. typedef const double *(*p_fun)(const double *, int);
  13. p_fun p1 = f1;
  14. auto p2 = f2; // C++0x automatic type deduction
  15. cout << "Using pointers to functions:\n";
  16. cout << " Address Value\n";
  17. cout << (*p1)(av,3) << ": " << *(*p1)(av,3) << endl;
  18. cout << p2(av,3) << ": " << *p2(av,3) << endl;
  19. // pa an array of pointers
  20. p_fun pa[3] = {f1,f2,f3};
  21. // auto doesn't work with list initialization
  22. // but it does work for initializing to a single value
  23. // pb a pointer to first element of pa
  24. auto pb = pa;
  25. cout << "\nUsing an array of pointers to functions:\n";
  26. cout << " Address Value\n";
  27. for (int i = 0; i < 3; i++)
  28. cout << pa[i](av,3) << ": " << *pa[i](av,3) << endl;
  29. cout << "\nUsing a pointer to a pointer to a function:\n";
  30. cout << " Address Value\n";
  31. for (int i = 0; i < 3; i++)
  32. cout << pb[i](av,3) << ": " << *pb[i](av,3) << endl;
  33. // what about a pointer to an array of function pointers
  34. cout << "\nUsing pointers to an array of pointers:\n";
  35. cout << " Address Value\n";
  36. // easy way to declare pc
  37. auto pc = &pa;
  38. cout << (*pc)[0](av,3) << ": " << *(*pc)[0](av,3) << endl;
  39. // slightly harder way to declare pd
  40. p_fun (*pd)[3] = &pa;
  41. // store return value in pdb
  42. const double * pdb = (*pd)[1](av,3);
  43. cout << pdb << ": " << *pdb << endl;
  44. // alternative notation
  45. cout << (*(*pd)[2])(av,3) << ": " << *(*(*pd)[2])(av,3) << endl;
  46. // cin.get();
  47. return 0;
  48. }
  49. // some rather dull functions
  50. const double * f1(const double * ar, int n)
  51. {
  52. return ar;
  53. }
  54. const double * f2(const double ar[], int n)
  55. {
  56. return ar+1;
  57. }
  58. const double * f3(const double ar[], int n)
  59. {
  60. return ar+2;
  61. }