(1)C++指针函数基础
文章来自 C++ Primer Plus 第7章 Pointers to Functions
函数是有地址的,它表示函数执行的入口。我们知道地址值并没有用,但是可以将地址值当做实参传入到其它函数中,这可以在不同的时期调用不同的函数。函数指针包括三点:如何获取函数地址,如何申明函数指针,如何调用函数。简单示例:
#include <iostream>
double betsy(int);
double pam(int);
// second argument is pointer to a type double function that
// takes a type int argument
void estimate(int lines, double (*pf)(int));
int main()
{
using namespace std;
int code;
cout << "How many lines of code do you need? ";
cin >> code;
cout << "Here's Betsy's estimate:\n";
estimate(code, betsy);
cout << "Here's Pam's estimate:\n";
estimate(code, pam);
return 0;
}
double betsy(int lns)
{
return 0.05 * lns;
}
double pam(int lns)
{
return 0.03 * lns + 0.0004 * lns * lns;
}
void estimate(int lines, double (*pf)(int))
{
using namespace std;
cout << lines << " lines will take ";
cout << (*pf)(lines) << " hour(s)\n";
}
输出如下:
wang@wang:~/c++$ ./a.out
How many lines of code do you need? 2
Here's Betsy's estimate:
2 lines will take 0.1 hour(s)
Here's Pam's estimate:
2 lines will take 0.0616 hour(s)