Error: passing xxx as 'this' argument of xxx discards qualifiers

Asked 2 years ago, Updated 2 years ago, 24 views

In the code below, cout << itr->getId() << " " << itr->getName() << endl; There's an error here, but I don't know why ㅜㅜ Why does const StudentT appear in the error when there is nothing specified as const in my code?

../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'int StudentT::getId()' discards qualifiers

../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'std::string StudentT::getName()' discards qualifiers

#include <iostream>
#include <set>

using namespace std;

class StudentT {

public:
    int id;
    string name;
public:
    StudentT(int _id, string _name) : id(_id), name(_name) {
    }
    int getId() {
        return id;
    }
    string getName() {
        return name;
    }
};

inline bool operator< (StudentT s1, StudentT s2) {
    return  s1.getId() < s2.getId();
}

int main() {

    set<StudentT> st;
    StudentT s1(0, "Tom");
    StudentT s2(1, "Tim");
    st.insert(s1);
    st.insert(s2);
    set<StudentT> :: iterator itr;
    for (itr = st.begin(); itr != st.end(); itr++) {
        cout << itr->getId() << " " << itr->getName() << endl;
    }
    return 0;
}

c++

2022-09-22 14:36

1 Answers

Objects stored in std::set are of type const. Therefore, the compiler makes an error because it tries to call getId() instead of constmember variable as const Student object.

To compile the above source code without errors, you must set the member functions to const.

int getId() const {
    return id;
}
string getName() const {
    return name;
}


2022-09-22 14:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.