C结构体中的函数指针与函数

1. 函数指针
一般的函数指针可以这么定义:
int(*func)(int,int);
表示一个指向含有两个int参数并且返回值是int形式的任何一个函数指针. 假如存在这样的一个函数:
int add2(int x,int y)
{
return x+y;
}
那么在实际使用指针func时可以这样实现:
func=&add2; //指针赋值,或者func=add2; add2与&add2意义相同
printf("func(3,4)=%d"n",func(3,4));

事实上,为了代码的移植考虑,一般使用typedef定义函数指针类型.
typedef int(*FUN)(int,int);
FUN func=&add2;
func();

2.结构体中包含函数指针

其实在结构体中,也可以像一般变量一样,包含函数指针变量.下面是一种简单的实现.
#include "stdio.h"
struct DEMO
{
int x,y;
int (*func)(int,int); //函数指针
};
int add2(int x,int y)
{
return x+y;
}
void main()
{
struct DEMO demo;
demo.func=&add2; //结构体函数指针赋值
printf("func(3,4)=%d"n",demo.func(3,4));
}
上面的文件保存为mytest.c,在VC6.0和gcc4中编译通过.

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2021-12-13
猜你喜欢
  • 2021-06-29
  • 2021-05-28
  • 2021-09-10
  • 2021-08-06
  • 2021-07-02
  • 2022-01-02
  • 2021-04-05
相关资源
相似解决方案