如何在C++中正确将带参数的函数传递给另一个函数?
函数嵌套调用传参的错误分析与修正
错误点梳理
你的修改代码存在三处核心错误:
- 函数指针声明错误:
hello函数的第三个参数int (*ptr)(int a)()是非法写法,带单个int参数的函数指针正确声明应为int (*ptr)(int),无需额外的(),参数名a在这里也不需要定义。 - 函数指针调用逻辑错误:
(*ptr)(a) ()完全混乱,代码里的a未定义,且写法不符合函数指针调用规范,正确调用应为ptr(传入的参数值)或(*ptr)(传入的参数值)。 - 参数传递逻辑错误:
add函数里hello(1,1, thirds(6))传递的是thirds(6)的返回值(int类型),但hello需要的是函数指针;同时int (*ptr)() = &thirds;的指针类型与thirds(现在接受int参数)不匹配。
修正后的代码
要实现从add传递参数给thirds,需要把要传递的参数也传给hello,让hello调用函数指针时使用该参数,修正后代码如下:
#include <iostream> int thirds(int a){ return a + 1; } template <typename T, typename B> int hello(T x, B y, int (*ptr)(int), int param){ int first = x + 1; int second = y + 1; int third = ptr(param); // 用传入的param作为thirds的参数 return first + second + third; } int add(){ // 函数指针类型与thirds匹配 int (*ptr)(int) = &thirds; // 传递函数指针和要传给thirds的参数6 return hello(1, 1, ptr, 6); } int main(){ std::cout << add(); return 0; }
验证输出
修正后代码运行结果为11,符合预期:
first = 1 + 1 = 2second = 1 + 1 = 2third = 6 + 1 = 7- 总和:
2 + 2 + 7 = 11
内容的提问来源于stack exchange,提问作者Senor Maldona
相关产品推荐
相关产品推荐

