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

Nak*_*kib 1 c++ struct pointers

我想传递一个结构来实现类似下面的函数(我知道我可以将单个成员传递给函数,如input(int age,string s)但我想传递整个结构,如输入(学生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;

}
Run Code Online (Sandbox Code Playgroud)

上面的代码没有产生正确的输出,我想使用上面的代码与指针,以获得预期的输出.

测试:如果我输入名称为"abc"并且年龄为10,则不会在main中打印

jua*_*nza 5

您的函数生成输入的本地副本.看起来你需要通过引用传递:

void input(student& s) { .... }
//                ^
Run Code Online (Sandbox Code Playgroud)

默认情况下,函数参数按值传递,因此此问题不是特定于类的.例如,

void increment_not(int i) { ++i; }

int i = 41;
increment_not(i);
std::cout << i << std::endl; // prints 41
Run Code Online (Sandbox Code Playgroud)