与数据项相似,函数也有地址。函数的地址是存储其机器语言代码的内存的开始地址。通常,这些地址对用户而言并不重要,但是对程序而言,却十分有用。例如:可以编写将另一个函数的地址作为参数的函数。这样一个函数就可以找到另外一个函数并运行它。与直接调用另外一个函数相比,这种方法很笨拙,但它允许在不同的时间传递不同函数的地址,这意味着可以再不同的时间使用不同的函数。
示例代码如下:
//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 parameter
double 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)来调用
运行效果如图: