Advertisement
uopspop

Untitled

Dec 29th, 2016
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int addInt(int n, int m){
  5.     return n + m;
  6. }
  7.  
  8. int timeInt(int n, int m){
  9.     return n * m;
  10. }
  11.  
  12. int main(){
  13. /************** function pointer *****************/
  14.     int sum = 0;
  15.  
  16.     // declare
  17.     int (*functionPtr)(int,int);
  18.  
  19.     // read values
  20.     // 1. assign memory address of a function to the pointer
  21.     functionPtr = addInt; //  或這樣寫: functionPtr = &addInt;
  22.  
  23.     // compute
  24.     sum = functionPtr(2,3); // 2 + 3 = 5 //  或這樣寫: sum = (*functionPtr)(2,3);
  25.  
  26.     // show result
  27.     printf("%d\n",sum);
  28.  
  29.     // read values
  30.     // 2. assign memory address of another function
  31.     functionPtr = timeInt;
  32.     // compute
  33.     sum = functionPtr(2,3); // 2 * 3 = 6
  34.     // show result
  35.     printf("%d\n",sum);
  36.  
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement