使用另一个对象的方法更改对象值

问题描述 投票:0回答:1

学生班:

class Student:public Persone, public Subjects{...}

学生班有这两个方法:

void setAr(int ar){
    this->arabic = ar;
}
int getAr(){
    return arabic;
}

我希望能够使用另一个班级老师更改学生笔记。

老师课上的方法:

void setStudentNote(Student student, int note){ bool access = false; for(int i=0;i<Groups.size();i++){ if(student.showGroup()==Groups[i]) access = true; } if(access){ if(Subject==Ar){ student.setAr(note); cout << student.getFname() << " "<<student.getLname() <<" " <<Subject << " note: " << note << endl; } }else{ cout << "error, this student is not in your group!"; } }
使用方法时 

void setStudentNote(Student Student, int note)Student.arabic 未更改。

c++ oop
1个回答
1
投票
您按值获取学生,这意味着每当您调用该函数时都会制作学生的副本,然后更改

copy。要更改原始版本,请使用(可变的)引用。

void setStudentNote(Student& student, int note)
请注意单词 

Student

 后面的 & 符号。 
Student&
 是对 
Student
 的非常量左值引用,这意味着对变量的修改将影响调用者的变量。

© www.soinside.com 2019 - 2024. All rights reserved.