【问题标题】:Passing values by reference into void function通过引用将值传递给 void 函数
【发布时间】:2018-03-28 05:09:54
【问题描述】:

我想创建一个程序,询问用户年、月和日。它使用一个 void 函数根据设定的标准检查每个值,以针对设定的范围执行验证。例如。年份必须是 > 1970 和

同样的函数也用于验证月份和日期范围。

我刚刚开始这一年,但在将值传递给函数时遇到了麻烦。

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

//declare function
void get_data();

int main()
{
//local variable declaration    
int input;
int criteria_1 = 1970;
int criteria_2 = 2020;

// ask for input and store
cout << "Enter the year: ";
cin >> input;

//call the function to validate the number    
get_data(input, criteria_1, criteria_2);

return 0;
}

//define function
void get_data(int x, int y, int z)
{
// set variable for what is being inputted
int input;

//repeat asking user for input until a valid value is entered
while (x <= y||x >= z){
    cout << "The valid range is >=" + y;
    cin >> x;
    input = x;
}
//display output on screen
cout << input << endl;

//reset variable for what was inputted 
input = 0;

return;
}

你能给我一些指导吗?我对此很陌生。谢谢。

【问题讨论】:

  • 你不需要在函数返回时“重置”局部变量——每个函数调用都有自己的。

标签: c++ function void


【解决方案1】:

如果您希望声明为 maininput 变量受到随后对 get_data(input, criteria_1, criteria_2) 的调用的影响,您必须使用与号 (&) 将相应的变量声明为左值引用,如下所示:

void get_data(int &x, int y, int z)

此外,您必须从get_data 中删除input 的声明(它是一个新变量,与main 中声明的变量不同)并写入

x = 0;

在函数的末尾。当调用get_data(input, criteria_1, criteria_2) 时,函数内部的x 被“硬连线”到传入的变量input 并且对x 所做的任何分配都对input 完成。

【讨论】:

  • 感谢马蒂亚斯。我已根据您的 cmets 添加了标准。当我运行程序时,我可以输入日期但没有验证。我遇到了分段错误。
【解决方案2】:

在声明您需要正确签名时。应该是

void get_data(int, int, int);

请记住,C++ 允许函数重载。所以正确的签名非常重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-05
    • 2021-02-08
    • 2023-03-08
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2013-02-19
    相关资源
    最近更新 更多