在void函数中调用另一个void函数遇编译错误,求解决方法
问题:void函数嵌套调用的编译错误解决
问题代码
#include <iostream> using namespace std; void test(int x,int n, double &test1); void ref(int a,int b, double &ref1); int main() { int x,n; double test1; cout<<"Enter x and n: "; cin>>x>>n; test(x,n,test1); cout<<"Your value is "<<test1; return 0; } void test(int x,int n, double &test1) { int a, b,ref1; ref(a,b,ref1); test1=x+n + ref1; } void ref(int a,int b, double &ref1) { ref1=a+b; }
编译错误信息
main.cpp: In function 'void test(int, int, double&)': main.cpp:32:17: error: cannot bind non-const lvalue reference of type 'double&' to an rvalue of type 'double' 32 | ref(a,b,ref1); | ^~~~ main.cpp:14:31: note: initializing argument 3 of 'void ref(int, int, double&)' 14 | void ref(int a,int b, double &ref1); | ~~~~~~~~^~~~
错误原因
- 类型不匹配:
test函数中声明的ref1是int类型,但ref函数的第三个参数要求是double&(double类型的引用),C++不允许将int变量直接绑定到double类型的引用上,这是触发编译错误的直接原因。 - 未初始化变量:
test函数里的a和b是局部变量,没有赋值就传递给ref函数,计算出的ref1会是随机垃圾值,逻辑存在问题。
修正方案及代码
针对问题做两处关键修改:
- 将
test函数中的ref1改为double类型,匹配ref函数的参数要求; - 给
a和b赋予合理的值(这里使用传入的x和n,符合最终计算test1 = x + n + ref1的逻辑)。
修正后的代码:
#include <iostream> using namespace std; void test(int x,int n, double &test1); void ref(int a,int b, double &ref1); int main() { int x,n; double test1; cout<<"Enter x and n: "; cin>>x>>n; test(x,n,test1); cout<<"Your value is "<<test1; return 0; } void test(int x,int n, double &test1) { // 给a、b赋值为传入的x和n,ref1改为double类型 int a = x, b = n; double ref1; ref(a,b,ref1); test1 = x + n + ref1; } void ref(int a,int b, double &ref1) { ref1 = a + b; }
代码说明
- 现在
ref函数的第三个参数ref1是double类型的引用,和test函数中声明的ref1类型一致,编译错误解决; a和b被赋值为x和n,ref函数计算的ref1是x + n,最终test1 = x + n + (x + n) = 2*(x+n),逻辑清晰且结果可预期。
内容的提问来源于stack exchange,提问作者B_Brink
相关产品推荐
相关产品推荐

