天天看点

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