c语言 一个函数返回结构体指针,详解C语言结构体中的函数指针

结构体是由一系列具有相同类型或不同类型的数据构成的数据集合。所以,标准C中的结构体是不允许包含成员函数的,当然C++中的结构体对此进行了扩展。那么,我们在C语言的结构体中,只能通过定义函数指针的方式,用函数指针指向相应函数,以此达到调用函数的目的。

函数指针

函数类型 (*指针变量名)(形参列表);第一个括号一定不能少。

“函数类型”说明函数的返回类型,由于“()”的优先级高于“*”,所以指针变量名外的括号必不可少。

注意指针函数与函数指针表示方法的不同,千万不要混淆。最简单的辨别方式就是看函数名前面的指针*号有没有被括号()包含,如果被包含就是函数指针,反之则是指针函数。

要声明一个函数指针,使用下面的语法:

1Return Type ( * function pointer's variable name ) ( parameters )

例如声明一个名为func的函数指针,接收两个整型参数并且返回一个整型值

1int (*func)(int a ,int b ) ;

可以方便的使用类型定义运用于函数指针:

1typedef int (*func)(int a ,int b ) ;

结构体中的函数指针我们首先定义一个名为Operation的函数指针:

1typedef int (*Operation)(int a ,int b );

再定义一个简单的名为STR的结构体

1

2

3

4

5typedef struct _str {

int result ;// 用来存储结果

Operation opt;// 函数指针

} STR;

现在来定义两个函数:Add和Multi:

1

2

3

4

5

6

7

8//a和b相加

int Add (int a,int b){

return a + b ;

}

//a和b相乘

int Multi (int a,int b){

return a * b ;

}

现在我们可以写main函数,并且将函数指针指向正确的函数:

1

2

3

4

5

6

7

8

9

10int main (int argc ,char **argv){

STR str_obj;

str_obj.opt = Add;//函数指针变量指向Add函数

str_obj. result = str_obj.opt(5,3);

printf (" the result is %d\n", str_obj.result );

str_obj.opt= Multi;//函数指针变量指向Multi函数

str_obj. result = str_obj.opt(5,3);

printf (" the result is %d\n", str_obj.result );

return 0 ;

}

运行结果如下:

1

2the result is 8

the result is 15

完整的代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28#include

typedef int (*Operation)(int a,int b);

typedef struct _str {

int result ;// to sotre the resut

Operation opt;// funtion pointer

} STR;

//a和b相加

int Add (int a,int b){

return a + b ;

}

//a和b相乘

int Multi (int a,int b){

return a * b ;

}

int main (int argc ,char **argv){

STR str_obj;

str_obj.opt = Add;//函数指针变量指向Add函数

str_obj. result = str_obj.opt(5,3);

printf ("the result is %d\n", str_obj.result );

str_obj.opt= Multi;//函数指针变量指向Multi函数

str_obj. result = str_obj.opt(5,3);

printf ("the result is %d\n", str_obj.result );

return 0 ;

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值