将结构传递给函数时出现意外结果

Unexpected result while passing struct to a function

本文关键字:意外 结果 函数 结构      更新时间:2023-10-16

我想传递一个结构来运行如下功能(我知道我可以传递单个成员来像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){....}