天天看點

C/C++開發: 函數指針用法

1 函數指針

函數名和變量名一樣,也對應一個位址,

實際上,每個函數在編譯後都對應一串指令,這些指令在記憶體中的位置,就是函數的位址

和變量位址一樣,我們可以用一個指針類型來表示函數的位址,指針變量也是變量

void (*p) (int)

變量名: p

變量類型: 函數指針 ,記作 void (int) *

傳回值為void,參數為int的函數

函數指針,表示的是函數代碼的位址

函數指針,可用于表示調用目标函數

函數名,就表示函數的位址

對于函數指針來說,&号可以省略

2 代碼示範

注意函數類型和指針類型要一樣

// C_Demo.cpp : 定義控制台應用程式的入口點。
//

#include "stdafx.h"

void example() {

}

int test1(int a){

  return a;
}

int test2(int a,int b){

  return a-b;
}

void test3(){
  printf("hello test3");
}

int _tmain(int argc, _TCHAR* argv[])
{
 

  // 取位址方式 %08x
  printf("example位址:%08x\n",example);
  printf("example位址:%08x\n",&example);
  printf("example位址:%08x\n",*example);

  // 取位址方式 %p
  printf("example位址:%p\n",example);
  printf("example位址:%p\n",&example);
  printf("example位址:%p\n",*example);


  //帶一個參數,且有傳回值
  int (*p1) (int);

  p1 = &test1;

  int  a = p1 (1);
  printf("p1:%d\n",a);

  //帶2個參數,且有傳回值
  int (*p2)(int,int);
  p2 = test2;

  printf("p2:%d\n",p2(5,8));


  // 無參數,無傳回值
  void (*p3) ();
  p3 = test3;
  p3();


  while (true)
  {

  }
  return 0;
}      

3 結果驗證

C/C++開發: 函數指針用法

4 擴充方法

   1 增強可讀性:使用typedef将函數指針起個别名

定義: typedef void (*FUN_TEST3) ();

調用:

FUN_TEST3 p4 ;

p4 = test3;

p4();

2 函數指針作為一個參數

定義:

void test4(FUN_TEST3 t3){

   t3();

}

調用 :test4(p4);