将结构传递给函数时出现意外结果
Unexpected result while passing struct to a function
我想传递一个结构来运行如下功能(我知道我可以传递单个成员来像input(int age,string s)一样函数,但我想像input(学生s)一样传递整个结构)
#include <iostream>
using namespace std;
struct student
{
string name;
int age;
};
void input(student s)
{
cout << "Enter Name: ";
cin >> s.name;
cout << "Enter age: ";
cin >> s.age;
}
int main(int argc, char *argv[]) {
struct student s1;
input(s1);
cout << "Name is: " << s1.name << endl;
cout << "Age is: " << s1.age << endl;
}
上面的代码没有产生正确的输出,我想将上面的代码与指针一起使用,以获得预期的输出。
测试:如果我输入名称为"abc"并将年龄输入为 10。它不会在主打印
您的函数会创建输入的本地副本。看起来您需要通过引用传递:
void input(student& s) { .... }
// ^
默认情况下,函数参数是按值传递的,因此此问题并非特定于类。例如
void increment_not(int i) { ++i; }
int i = 41;
increment_not(i);
std::cout << i << std::endl; // prints 41
你的函数按值传递student s
,这就是为什么main
中的变量s1
不会改变的原因。
将其更改为传递引用:
void input(student& s)
// ^
您需要通过引用传递结构,现在您正在通过副本传递它,因此无论进行什么更改,它们都在传递对象的副本上。
void input(student& s){....}
相关文章:
- 尝试将字符串/字符转换为整数会产生意外结果
- RapidXML - 代码创建意外结果
- 类中静态函数C++意外结果
- 指针数组中的意外结果
- 使用指针访问数组元素时出现意外结果
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++:比较运算符>和字符串文本的意外结果
- 具有意外结果的 C++ 闭包
- yaml-cpp 比较的意外结果
- 每次都出现意外结果
- 在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)
- 如何避免 std::abs 的意外结果?
- 使用嵌套 if 语句的意外结果
- A ^= B ^= A ^= B;C# Visual Studio 中的意外结果
- 逻辑错误,我将获得意外结果
- 在 c++ 中使用异步的意外结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 执行递增和递减时"cout"链接会产生意外结果
- OpenCL - 内核方法返回意外结果
- C++使用 std::get_time 解析 YYMMDD ISO 8601 日期字符串会得到意外结果