您的位置:首页 > 编程语言 > C语言/C++

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

2017-03-12 14:15 435 查看

代码功能

从命令行读取格式为
函数名 数值
的输入,例如:
log10 1000


在命令行输出调用对应函数名的函数计算结果,例如:
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 : log10
2
2
log10 1000
3

--------------------------------
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
,可以,那就按照下面这样写,并且全部满足给
int
double
这种格式的函数都可以被
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;


识别字符串调用对应函数

命令行标准读入代表函数名的字符串pS 以及 想要计算的数值

通过哈希表找到对应的函数指针FunTab[pS]

通过函数指针直接 调用函数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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 函数指针 函数
相关文章推荐