简体   繁体   中英

error: passing ‘const std::__cxx11::list<>’ as ‘this’ argument discards qualifiers

I have a little problem and can't find a way to fix it..

In my.hpp file I have declared these two functions and struct but getting the error 'passing 'const std::__cxx11::list<>' as 'this' argument discards qualifiers.'

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

And in.cpp file I have tried to do:

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

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

How can I make this work?

const std::list<Student>& GetStudents() const;

and

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

are in conflict. You have a contract to not modify the list you get from GetStudents() , but you try to do that with push_back .

Solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM