代码功能
从命令行读取格式为 函数名 数值 的输入,例如: log10 1000在命令行输出调用对应函数名的函数计算结果,例如: log10(1000) = 3
完整源码
#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;
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);
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;
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/
转载请注明原文地址: https://ju.6miu.com/read-33346.html