You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中类内函数修改构造初始化成员变量失效问题解决

问题:Student类的edit_info修改操作不生效

我定义了Student类,通过构造函数初始化name和age成员变量,后续需要允许学生修改这些信息。编写了如下代码尝试实现,但edit_info函数的修改操作并未生效:

class Student{
public:
    string name;
    int age;
    int grades[3];
    int assignments[4];

Student(string name, int age){
    this->name = name;
    this->age = age;
}

void edit_info(){
    string newName;
    int newAge;

    cout<<"Set new name:";
    cin>>newName;
    cout<<"Set new age:";
    cin>>newAge;

    this->name=newName;
    this->age=newAge;
    
}
void show_info(){
    cout<<name<<"\n";
    cout<<age<<"\n";
}
};

选择操作学生的代码:

if(input == "studentOne"){
        cout<<"You are now student 1\n";
        cout<<"What is your name:";
        cin >> s1_name;
        cout<<"How old are you:";
        cin >> s1_age;
        Student student1(s1_name, s1_age);
        while(true){
            CMD(student1);
        }
}

CMD函数代码:

void CMD(Student student){
string command;
cout<<"Type your command(edit_info, submit_assignments, sitFortest, show_info):";
cin>>command;

if(command=="edit_info"){
    student.edit_info();
}
else if(command=="show_info"){
    student.show_info();
}
}

问题根源

问题出在CMD函数的参数传递方式:当前使用的是值传递,每次调用CMD(student1)时,会创建一个student1的副本对象传入函数。edit_info修改的只是这个副本的name和age,函数执行完毕后副本会被销毁,原对象student1的属性完全没被改动,所以看起来修改没生效。

解决方案

把CMD函数的参数改成引用传递,这样函数内部操作的就是原对象本身,修改会直接作用在student1上。修改后的CMD函数代码如下:

void CMD(Student &student){ // 添加&改为引用传递
string command;
cout<<"Type your command(edit_info, submit_assignments, sitFortest, show_info):";
cin>>command;

if(command=="edit_info"){
    student.edit_info();
}
else if(command=="show_info"){
    student.show_info();
}
}

修改后再调用edit_info,就能正常修改原Student对象的name和age了,调用show_info可以看到更新后的结果。

内容的提问来源于stack exchange,提问作者Dot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:10:26