【问题标题】:How to add class element to vector inside of another private class如何将类元素添加到另一个私有类中的向量
【发布时间】:2020-03-01 19:01:00
【问题描述】:

我制作了一个由向量​​组成的大学课程,其中学位是另一个由向量​​组成的课程。所有向量都是私有的,我想使用 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 对象添加新度数时,我可以在显示它们时看到结果,但是当我向这些度数添加新学生时,我看不到任何变化。两个学位仍然为空。我觉得我编辑了他们的本地副本,因此我没有看到添加的学生。但是,我不知道如何修复它...这是 setter 的代码:

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;
}

【问题讨论】:

  • "set" 不是命名添加要列出的内容的方法的好方法。这可能看起来没什么大不了,但如果不记住第二个,就不可能理解第一个 sn-p 的工作原理。
  • 让我猜猜:你有Java背景,现在正在学习C++?这就是对象在 Java 中的工作方式,但 C++ 不是 Java。您的吸气剂返回向量中对象的完整副本,并且修改它对向量中的对象绝对没有任何作用。 C++ 不能以这种方式工作。也许你想返回一个引用而不是一个对象?
  • 就像 Sam 所写的那样,C++ 传递值的方法与一般的对象语言略有不同。例如,当您没有理由创建对象的副本(这对性能不利)时,您不应该在任何情况下真正按值传递对象。编译器应该优化像您这样的简单案例,但请记住,当您的程序变得更大时。实际上,如果你想真正优化它,你可以查找 r-value 构造函数和方法emplace,但这是高级的东西。

标签: c++ class vector


【解决方案1】:

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

Degree &getDegree(int i);

Student &getStudent(int i);

【讨论】:

  • 另外,每个字段可能应该有两个 getter。一个应该是const,因此可以在 const 对象上使用它。
猜你喜欢
  • 2022-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多