c++ - 如何将类元素添加到另一个私有类中的向量
问题描述
我制作了一个由向量组成的大学课程,其中学位是另一个由向量组成的课程。所有向量都是私有的,我想使用 setter 和 getter 来修改它们。在 main() 中测试其功能时,我注意到奇怪的行为:
University ua;
ua.setDegree(Degree("Computer Science"));
ua.getDegree(0).setStudent(Student("1101","Ria",true));
ua.getDegree(0).setStudent(Student("1102","Ava",false));
ua.setDegree(Degree("Biotechnology"));
ua.getDegree(1).setStudent(Student("1104","Vry",false));
ua.showDegrees();
在向 ua 对象添加新度数时,我可以在显示它们时看到结果,但是当我向这些度数添加新学生时,我看不到任何变化。两个学位仍然为空。我觉得我编辑了他们的本地副本,因此我没有看到添加的学生。但是,我不知道如何修复它......这是设置器的代码:
class University {
private:
vector<Degree> all;
int n;
public:
Degree getDegree(int i) {return all.at(i);}
void setDegree(Degree degree) {all.push_back(degree); n++;}
int getN() {return n;}
void showDegrees() { for(int i=0; i<n; i++) {cout<<endl<<getDegree(i).getName()<<endl;} }
University() { this->n = 0; } };
class Degree {
private:
string name;
vector<Student> all;
int n;
public:
string getName() {return name;}
void setName(string name) {this->name = name;}
Student getStudent(int i) {return all.at(i);}
void setStudent(Student student) {all.push_back(student); n++;}
vector<Student> getAll() {return all;}
int getN() {return n;}
Degree(string);
Degree() {} };
Degree::Degree(string name) {
this->name = name;
n = 0;
}
解决方案
您的 getter 返回您的类中包含的对象的副本。如果希望能够直接修改类对象,则需要通过引用返回:
Degree &getDegree(int i);
Student &getStudent(int i);
推荐阅读
- c++ - 是否可以解释为什么返回 21
- jquery - 使用ajax在Django中将数据下载为Excel文件
- javascript - 使用带有 React.useEffect 的事件监听器
- python - 自我对象和非自我对象之间有什么区别,特别是在 Tkinter 类中?
- docusignapi - 对现有用户的 `/users` 的 POST 请求会导致重新发送激活电子邮件
- tableau-api - 如何复制 Tableau 数据提取逻辑?
- angular - 将现有的 Ionic / Firebase 项目部署到新的 Firebase 托管项目
- c# - VS 2019 无法通过实体框架加载 MySQL 数据库
- java - 将 Spring Boot 2.2.6 迁移到 Spring Boot 2.3.0 时的问题
- elasticsearch - 布尔过滤器不只显示弹性搜索中的过滤数据