函数指针的用法

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


示例代码如下:

//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)来调用

运行效果如图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值