[C++]C++ 函数指针 实现 函数名字符串 到 函数调用 cmath.h

来源:互联网 发布:安卓电子书制作软件 编辑:程序博客网 时间:2024/05/16 06:25

代码功能

  1. 从命令行读取格式为 函数名 数值 的输入,例如: log10 1000
  2. 在命令行输出调用对应函数名的函数计算结果,例如: log10(1000) = 3

完整源码

// C++ code#include <iostream>#include <cmath>#include <map>typedef double (* PtrFun) (double x);class FunctionEntry{public:    PtrFun pFun;        std::string strFun;};std::map <std::string, PtrFun> FunTab;FunctionEntry funEntry = {std::log10, "log10"};int main(){    std::cout << " funEntry.strFun : " << funEntry.strFun << std::endl;    FunTab["log10"] = funEntry.pFun;    std::cout   <<  std::log10((double)100)         <<  std::endl;    std::cout   <<  FunTab["log10"]((double)100)    <<  std::endl;    std::string pS;     double x;    // log10 1000    std::cin >> pS >> x;    std::cout << FunTab[pS](x) << std::endl;    return 0;}

测试运行

 funEntry.strFun : log1022log10 10003--------------------------------Process exited after 5.727 seconds with return value 0请按任意键继续. . .

代码分析

引入标准

  • 利用C库自带的函数,调用之直接进行计算;
#include <cmath>

函数指针

  • 利用关键词 typedef 声明一种新的类型 PtrFun
typedef double (* PtrFun) (double x);PtrFun pFun;
  • 两种写法等价,
    • pFun是一个指向带有double类型的参数返回double类型的函数的指针,例如: 函数sin(π)cos(π)都接受一个double类型的参数π(3.1415926...),同时会返回相应的一个double类型的结果0.0或者-1.0;
    • 即只要是接受double类型又返回double类型的函数,诸如sin cos log log10 等等都可以用这个函数指针来指向;
double (* pFun) (double x);
  • 可不可以给一个int 返回一个double,可以,那就按照下面这样写,并且全部满足给intdouble这种格式的函数都可以被pFun2 指向了;
double (* pFun2) (int x);

哈希表

  • 建立字符串与对应函数指针之间的联系
std::map <std::string, PtrFun> FunTab;

函数地址

  • C库中函数名字就是函数地址,用std::log10 就是调用以10为底求对数,C++能懂!
FunctionEntry funEntry = {std::log10, "log10"};
  • 直接调用函数和通过函数指针调用函数的对比,效果是一样的,都会输出2,因为(100 = 10^2);
// map的写法,使得字符串log10 真正与 函数 std::log10的指针建立起了联系,从而能在O(1)的时间内访问到;    FunTab["log10"] = funEntry.pFun;    std::cout   <<  std::log10((double)100)         <<  std::endl;    std::cout   <<  FunTab["log10"]((double)100)    <<  std::endl;

识别字符串调用对应函数

  1. 命令行标准读入代表函数名的字符串pS 以及 想要计算的数值
  2. 通过哈希表找到对应的函数指针FunTab[pS]
  3. 通过函数指针直接 调用函数FunTab[pS] (x)
std::string pS;     double x;    // log10 1000    std::cin >> pS >> x;    std::cout << FunTab[pS](x) << std::endl;

引用参考

[1] cmath
http://www.cplusplus.com/reference/cmath/
[2] C++ STL map
http://www.cplusplus.com/reference/map/
[3] C++ 函数指针 Pointers to functions
http://www.cplusplus.com/doc/tutorial/pointers/
[4] 《C++实践之路》(C++ In Action Industrial Strength Programming) 第5章 5.5函数表
http://www.relisoft.com/book/

0 0
原创粉丝点击