【发布时间】:2022-10-04 19:23:18
【问题描述】:
请耐心等待,因为我是编码新手。
我试图弄清楚如何将 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);
| ~~~~~~~~^~~~
我正在尝试在void test 函数中使用void ref 函数并在main 函数下打印出来。我可以这样做吗?
【问题讨论】:
-
错误消息(您应该将其作为文本放入问题中,而不是放入图像中,请参阅How to Ask)对问题不是特别清楚,但只需查看
test和@ 中的ref1的类型987654329@。我想你应该注意到那里有问题... -
机械地,是的,如果参数与签名匹配,
test函数可以调用ref函数。但是在初始化失败后使用变量a和b是错误的。 -
另外,如果您将未初始化的
a和b从test传递给它们,您期望ref中的a和b的值是多少? -
而且,除非您尝试练习引用,否则没有理由将结果写入引用输出参数。您可以只从函数返回计算结果(在将
void替换为正确的返回类型之后)并将返回值分配给调用者中的相应变量。这样自然多了。 -
这些函数不返回任何结果(声明为
void)这一事实与问题无关。您需要提供的参数与类型中声明的参数相匹配。