首页 > 解决方案 > 如何将类元素添加到另一个私有类中的向量

问题描述

我制作了一个由向量​​组成的大学课程,其中学位是另一个由向量​​组成的课程。所有向量都是私有的,我想使用 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;
}

标签: c++classvector

解决方案


您的 getter 返回您的类中包含的对象的副本。如果希望能够直接修改类对象,则需要通过引用返回:

Degree &getDegree(int i);

Student &getStudent(int i);

推荐阅读