lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[c/cpp]:  函数的指针和函数数组的指针

 

 

 

 

一、 函数指针

 

  1、  函数的指针:指向函数的指针,叫做“函数的指针”。

 

  2、  函数数组的指针:指向函数数组的指针,叫做“函数数组的指针”。

 

 

 

 

二、代码:  g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 
 5 void 
 6 msg1
 7 (void)
 8 {
 9     printf("\t[msg1]#\tvoid msg1()\n");
10 }
11 
12 
13 void
14 msg2
15 (void)
16 {
17     printf("\t[msg2]#\tvoid msg2()\n");
18 }
19 
20 
21 void
22 output
23 ()
24 {
25     printf("\n[os]# SYSTEM INFORMATIONS\n");
26 }
27 
28 
29 int 
30 main
31 ()
32 {
33     output();
34     
35     //  'fa' pointers to array of functions
36     //  'fa' is an array
37     //  similar:  fa[] = {fun1, fun2, ... }; 
38     //        fun1, fun2 are functions;
39     //        fun1 and fun2 have same format of parameter type and return value type. 
40     //        about type of value:  'C++' is able to use syntax 'template<...>' for types about parameters and return value.
41     void (*fa[])(void) = { msg1, msg2 };
42     
43     fa[0]();
44     fa[1]();
45 
46     return 0;
47 }

 

 

 

 

三、运行

[os]# SYSTEM INFORMATIONS
    [msg1]#    void msg1()
    [msg2]#    void msg2()

 

 

 

 

四、参考资料

 

  1、  c函数指针和回调函数  -  https://www.runoob.com/cprogramming/c-fun-pointer-callback.html

 

  2、  c/cpp 在线编辑工具  -  https://coliru.stacked-crooked.com/

 

posted on 2024-05-22 03:53  lnlidawei  阅读(3)  评论(0编辑  收藏  举报