【问题标题】:error: passing ‘const std::__cxx11::list<>’ as ‘this’ argument discards qualifiers错误:将“const std::__cxx11::list<>”作为“this”参数传递会丢弃限定符
【发布时间】:2020-02-16 03:18:01
【问题描述】:

我有一个小问题,找不到解决方法..

在我的 .hpp 文件中,我声明了这两个函数和结构,但收到错误“将‘const std::__cxx11::list’作为‘this’参数丢弃限定符。”

struct Student {
    std::string name;
    std::string student_id;

};

class StudentRegistry {

public:
    StudentRegistry(){}
    void Add(const Student &t);
    const std::list<Student>& GetStudents() const;

private:
    std::list<Student> students;
};

在 .cpp 文件中我尝试过这样做:

void StudentRegistry::Add(const Student &t){
    this->GetStudents().push_back(t);
}

const std::list<Student>& StudentRegistry::GetStudents() const{
    return students;
}

我怎样才能做到这一点?

【问题讨论】:

    标签: c++ constants


    【解决方案1】:
    const std::list<Student>& GetStudents() const;
    

    this->GetStudents().push_back(t);
    

    有冲突。您有一个合同修改您从GetStudents() 获得的列表,但您尝试使用push_back 进行修改。

    解决方案:

    void StudentRegistry::Add(const Student& t) {
        students.push_back(t);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多