[C++] 錯誤:將xxx作為xxx的“this”參數丟棄限定符


Answers

不修改類實例的成員函數應聲明為const

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

任何時候當你看到“丟棄限定符”時,它都會談論constvolatile

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

一致:

cout << itr->getId() << " " << itr->getName() << endl;

它給出了一個錯誤:

../main.cpp:35:錯誤:將'const StudentT'作為'int'的參數'int StudentT :: getId()'丟棄限定符

../main.cpp:35:錯誤:將'const StudentT'作為'std :: string'的'this'參數傳遞給StudentT :: getName()'拋棄限定符

這段代碼有什麼問題? 謝謝!







Tags