通过引用将值传递到void函数中

Passing values by reference into void function

本文关键字:void 函数 值传 引用      更新时间:2023-10-16

我想创建一个询问用户一年,月和一天的程序。它使用一个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;
}

您能给我一些指导吗?我是新的。谢谢。

如果您希望input变量声明为main受到随后呼叫get_data(input, criteria_1, criteria_2)的影响,则必须将相应变量声明为LVALUE参考,例如使用ampersand(&amp;(,:

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进行。

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

void get_data(int, int, int);

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