lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  430 随笔 :: 1 文章 :: 3 评论 :: 21万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 29
30 31 1 2 3 4 5

[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   lnlidawei  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-05-22 OS: CentOS8本地源配置过程
点击右上角即可分享
微信分享提示