函数指针用法

基础:

  1. 获取到函数的地址
  2. 声明一个函数指针
  3. 使用函数指针来调用函数

获取函数地址
函数的地址就是函数名,要将函数作为参数传递,必须传递函数名

声明函数指针
声明指针的时候,必须指定指针指向的数据类型。同样的,声明指向函数的指针时,必须指定指针指向的函数类型,这意味着声明应当指定函数的返回类型以及函数的参数列表。例如:

double cal(int);	//prototype
double (*pf)(int);	//指针pf指向的函数,输入参数为int,返回值为double
pf = cal;	//指针赋值

如果将指针作为函数的参数传递:
void estimate(int lines, double (*pf)(int));
使用指针调用函数

double y = cal(5);	//通过函数调动
double y = (*pf)(5);//通过指针调用 推荐
double y = pf(5);	//这样也对,但是不推荐

函数指针的一般用法

#include <iostream>
#include <algorithm>
#include <cmath>
 
using namespace std;
 
double cal_m1(int lines)
{
	return 0.05 * lines;
} 
 
double cal_m2(int lines)
{
	return 0.5 * lines;
}
 
void estimate(int line_num, double (*pf)(int lines))
{
	cout << "The " << line_num << " need time is: " << (*pf)(line_num) << endl; 
}
 
 
 
int main(int argc, char *argv[])
{
	int line_num = 10;
	// 函数名就是指针,直接传入函数名
	estimate(line_num, cal_m1);
	estimate(line_num, cal_m2); 
	return 0;
}

函数指针数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值