函数指针的用法
来源:互联网 发布:nginx 绑定子域名 编辑:程序博客网 时间:2024/04/28 16:24
与数据项相似,函数也有地址。函数的地址是存储其机器语言代码的内存的开始地址。通常,这些地址对用户而言并不重要,但是对程序而言,却十分有用。例如:可以编写将另一个函数的地址作为参数的函数。这样一个函数就可以找到另外一个函数并运行它。与直接调用另外一个函数相比,这种方法很笨拙,但它允许在不同的时间传递不同函数的地址,这意味着可以再不同的时间使用不同的函数。
示例代码如下:
//fun_ptr.cpp -- pointers to functions #include <iostream>void estimate ( int lines, double (*pf) (int) );//second parameter is a pointer to a type doubel function //that takes a type int parameterdouble algrithm_1 (int lns);double algrithm_2 (int lns); int main(){using namespace std;int code;cout << "how many lines of code do you need?" << endl;cin >> code;cout << " Here is algrithm_1 estimate:\n"; estimate ( code, algrithm_1); // 函数名作为参数传递给estimate()cout << " Here is algrithm_2 estimate:\n"; estimate ( code, algrithm_2); // 函数名作为参数传递给estimate()cin.get();cin.get();return 0;}double algrithm_1 (int lns) // 函数名作为参数被运行{return 0.05 * lns;}double algrithm_2 (int lns) // 函数名作为参数被运行{return 0.03 * lns + 0.004 *lns * lns;}void estimate ( int lines, double (*pf) (int) ) // 第二个参数声明为函数指针,被指向的函数有一个int参数并返回double{using namespace std;cout << lines << " lines will take ";cout << (*pf)(lines) << " houur(s)\n"; //利用函数指针pf调用另外一个函数} //也可以采用pf(lines)来调用
运行效果如图:
0 0
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的用法
- 函数指针的相关用法
- C函数指针的用法
- 利用GDI+基于WIN32实现桌面雪花效果(二)
- 关于linux fork()函数的一道题
- jquery.lazyload.js实现图片异步延迟加载
- uva 709 &poj 1093 - Formatting Text (dp之小白告一段落)
- MySQL优化 之 Discuz论坛优化
- 函数指针的用法
- map的collect和spill过程解析
- 运行第一个 Delphi 7/XE2/Lazarus 的 Windows 程序,并熟悉 IDE
- 输入字符数字串输出保存数字串
- 13-Fibonacci数
- java的动态代理(JDK和cglib)
- 在linux下怎么打包直接运行的node-webkit桌面应用
- 实现自己的http server
- 2014年3月腾讯广研班笔试经验