通过引用将值传递到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;
}
您能给我一些指导吗?我是新的。谢谢。
如果您希望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 允许函数过载。因此,正确的签名非常重要。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 如何将指针从一个void函数传递到另一个C++
- 为什么我在使用void函数时得到错误代码C2276
- 指针没有更新它在void函数内部指向的值
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- void 函数可以传递值参数吗?
- 在 void 函数中使用 #include 变量C++
- 如何在 C++ 中将 void 函数传递给 void 指针
- 使用运算符调用 void 函数时出错<set>
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- C++ :: 如何捕获由 void 函数创建的矩阵
- 如何将一个 void 函数传递给另一个 void 函数?
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- C++命名空间中调用 void 函数的错误
- 当数组位于两个循环之间时,您可以调用数组的 void 函数吗?
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 查找素数:错误:控件到达非void函数的末尾