繁体   English   中英

通过引用将值传递给void函数

[英]Passing values by reference into void function

我想创建一个程序,要求用户输入年,月和日。 它使用一个void函数根据设置的标准检查每个值,以对设置的范围进行验证。 例如。 年份必须是> 1970和<2020。

相同的功能也可用于验证月份和日期范围。

我刚从一年开始,但是在将值传递到函数中遇到麻烦。

#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;
}

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

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

void get_data(int, int, int);

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

如果要使声明为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内的x被“硬连线”到传入的变量input并且对x所做的任何赋值都被input

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM