[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()'抛弃限定符

这段代码有什么问题? 谢谢!




Links



Tags

c++ c++