努力学习的阿信 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条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格