【问题标题】:Calling a void function to another void function BEFORE calling to the main function在调用主函数之前调用一个 void 函数到另一个 void 函数
【发布时间】: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 函数。但是在初始化失败后使用变量ab是错误的。
  • 另外,如果您将未初始化的abtest 传递给它们,您期望ref 中的ab 的值是多少?
  • 而且,除非您尝试练习引用,否则没有理由将结果写入引用输出参数。您可以只从函数返回计算结果(在将 void 替换为正确的返回类型之后)并将返回值分配给调用者中的相应变量。这样自然多了。
  • 这些函数不返回任何结果(声明为void)这一事实与问题无关。您需要提供的参数与类型中声明的参数相匹配。

标签: c++ function void


【解决方案1】:

您的 ref() 函数在其第三个参数中采用对 double 的非常量引用。但是,您的 test() 函数正在使用 int 变量初始化该参数。因此,编译器必须执行从int 到临时double 的隐式转换,但随后会失败,因为非常量引用无法绑定到临时对象,因此会出现编译器错误。

您需要更改test() 以将double 变量传递给ref()(就像main() 在调用test() 时所做的那样),例如:

void test(int x,int n, double &test1)
{
    int a, b;
    double ref1; // <-- here
    ref(a,b,ref1);
    test1=x+n + ref1;
}

另请注意,test() 并未使用任何值初始化其ab 变量,但仍将它们传递给ref(),然后将它们的值相加并将结果分配给ref1。该总和将有未定义的行为ref1 的结果值为不定.你也需要解决这个问题。

【讨论】:

    猜你喜欢
    • 2014-11-13
    • 2023-01-28
    • 1970-01-01
    • 2017-08-26
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2021-06-06
    相关资源
    最近更新 更多