努力学习的阿信 2021-04-15 23:02 采纳率: 90%
浏览 30
已采纳

函数作为形参传递给函数时可以使用const修饰形参吗?

最近在学习指针函数时遇到一个问题,我先上代码:

#include<iostream> 
using std::cin;
using std::cout;
using std::endl;

double besty(int);
double pam(int);

void estimate(int, double (* ptr)(int));//double (*ptr)(int) 代表的是指向函数地址的指针

int main() {
	int code;
	cout << "How many llines of code do you need ?" << endl;
	cin >> code;
	cout << "Here's Besty's estimate :\n";
	//将函数作为参数传递时,传递函数的地址时仅需要将函数名传递就可以
	estimate(code, besty);
	cout << "Here's Pam's estimate :\n";
	estimate(code, pam);
	return 0;
}

double besty(int line) {
	return 0.05 * line;
}

double pam(int line) {
	return 0.03 * line + 0.0004 * line * line;
}

void estimate(int lines, double (* ptr)(int)) {
	cout << lines << " lines will take ";
	cout << (*ptr)(lines) << " hour(s)\n";
}

指针函数作为形参这个知识点我是能看懂的,但是之后我就在想一个问题,

void estimate(int, double (* ptr)(int));

这个函数的参数列表中有函数地址作为参数并使用指针指向这个地址,那么这个指针可以用const修饰吗,如果可以,函数原型应该怎么写,然后有需要注意的地方吗?求各路大佬指点迷津!!!

  • 写回答

2条回答 默认 最新

  • lemon-l 2021-04-15 23:14
    关注

    可以这么写void estimate(int lines, double (* const ptr)(int));这样ptr就是个const函数指针,无法改变ptr的值

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Error in check.length("fill") : 'gpar'成分'fill'的长度不能为零
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导