에러: passing xxx as 'this' argument of xxx discards qualifiers

조회수 7755회

발생하는 문제 및 실행환경

밑의 코드에서 cout << itr->getId() << " " << itr->getName() << endl; 여기서 에러가 나는데 왜 나는지 모르겠어요 ㅜㅜ 제 코드에서는 const로 지정한 게 하나도 없는데 에러에 const StudentT는 왜 뜨는 건가요?

에러내용

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

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    std::set에 저장되는 객체는 const형 객체입니다. 따라서 const Student객체로 const멤버 변수가 아닌 getId()를 부르려고 해서 컴파일러에서 에러를 내는 것입니다.

    위의 소스코드를 에러 없이 컴파일하려면 멤버 함수들을 const로 설정해야 합니다.

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

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)