• C++ code:函数指针数组


    函数指针作为一种数据类型,当然可以作为数组的元素类型。例如,要实现用菜单来驱动函数调用的程序框架,则用函数指针数组来实现就比较容易维护。

     1 #include<iostream>
     2 using namespace std;
     3 
     4 typedef void(*MenuFun)();
     5 void f1(){ cout << "good!
    "; }
     6 void f2(){ cout << "better!
    "; }
     7 void f3(){ cout << "best!
    "; }
     8 
     9 int main()
    10 {
    11     MenuFun fun[] = {f1,f2,f3};
    12     for (int choice = 1; choice;)
    13     {
    14         cout << "1-----display good
    "
    15             << "2-----display better
    "
    16             << "3-----display best
    "
    17             << "0-----display exit
    "
    18             << "Enter your choice:";
    19         cin >> choice;
    20         switch (choice)
    21         {
    22         case 1:fun[0](); break;
    23         case 2:fun[1](); break;
    24         case 3:fun[2](); break;
    25         case 0:return 0;
    26         default:cout << "you entered a wrong key.
    ";
    27         }
    28     }
    29 }

    程序第4行首先定义了一个函数指针类型MenuFun。若前面无typedef,则后面部分就是一个函数指针定义,所以,正因为有了typedef,MenuFun就是函数指针的类型名,可以以此创建函数指针,但其本身并不是函数指针。

    在第11行,根据MenuFun创建了一个函数指针数组fun,并予以初始化。初始化的值每个都是同类型的函数名,它们在第5、6、7行定义,接下来就是循环处理键盘输入,每当输入值为1,或2或3时,显示good、better、best等字样。同一功能的程序,也可以用向量来实现,当然从眼前的小结构程序来看,其方便性并不明显,以下是改用向量来实现的代码:

     1 #include<iostream>
     2 #include<vector>
     3 using namespace std;
     4 
     5 typedef void(*MenuFun)();
     6 void f1(){ cout << "good!
    "; }
     7 void f2(){ cout << "better!
    "; }
     8 void f3(){ cout << "best!
    "; }
     9 
    10 int main()
    11 {
    12     vector<MenuFun> fun(3);
    13     fun[0] = f1, fun[1] = f2, fun[2] = f3;
    14     for (int choice = 1; choice;)
    15     {
    16         cout << "1-----display good
    "
    17             << "2-----display better
    "
    18             << "3-----display best
    "
    19             << "0-----display exit
    "
    20             << "Enter your choice:";
    21         cin >> choice;
    22         if (choice > 0 && choice < 4) fun[choice - 1]();
    23         else if (choice == 0) return 0;
    24         else cout << "you entered a wrong key.
    ";
    25     }
    26 }

  • 相关阅读:
    ffmpeg 合并文件
    win10 设备摄像头,麦克风,【隐私】权限
    负载均衡,过载保护 简介
    《用Python做科学计算》 书籍在线观看
    Getting Started with OpenMP
    Algorithms & Data structures in C++& GO ( Lock Free Queue)
    PostgreSQL新手入门
    Ubuntu 网络配置
    QT 4.7.6 驱动 罗技C720摄像头
    使用vbs脚本添加域网络共享驱动器
  • 原文地址:https://www.cnblogs.com/ariel-dreamland/p/9081587.html
Copyright © 2020-2023  润新知