亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

錯誤:將xxx作為xxx的'this'參數傳遞丟棄限定符

錯誤:將xxx作為xxx的'this'參數傳遞丟棄限定符

C++
jeck貓 2019-09-18 13:30:22
#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 StudentT :: getId()'的'this'參數傳遞,丟棄限定符../main.cpp:35:錯誤:將'const StudentT'作為'std :: string的'this'參數傳遞StudentT :: getName()'丟棄限定符這段代碼出了什么問題?謝謝!
查看完整描述

3 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

其中的對象std::set存儲為const StudentT。因此,當您嘗試getId()使用const對象調用時,編譯器會檢測到問題,主要是您在const對象上調用非const成員函數,這是不允許的,因為非const成員函數沒有PROMISE不修改對象; 所以編譯器會做一個安全的假設,getId()可能會嘗試修改對象,但同時,它也注意到對象是const; 所以任何修改const對象的嘗試都應該是一個錯誤。因此編譯器會生成錯誤消息。


解決方案很簡單:將函數const設為:


int getId() const {

    return id;

}

string getName() const {

    return name;

}

這是必要的,因為現在你可以打電話getId()和getName()在const對象為:


void f(const StudentT & s)

{

     cout << s.getId();   //now okay, but error with your versions

     cout << s.getName(); //now okay, but error with your versions

}

作為旁注,您應該實現operator<為:


inline bool operator< (const StudentT & s1, const StudentT & s2)

{

    return  s1.getId() < s2.getId();

}

注意參數現在是const參考。


查看完整回答
反對 回復 2019-09-18
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

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


int getId() const {

    return id;

}

string getName() const {

    return name;

}

任何時候你看到“丟棄限定符”,它正在談論const或volatile。


查看完整回答
反對 回復 2019-09-18
?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

實際上C ++標準(即C ++ 0x草案)說(tnx to @Xeo&@Ben Voigt指出這一點):


23.2.4關聯容器

5對于set和multiset,值類型與鍵類型相同。對于map和multimap,它等于pair。關聯容器中的鍵是不可變的。

6關聯容器的迭代器是雙向迭代器類別。對于值類型與鍵類型相同的關聯容器,iterator和const_iterator都是常量迭代器。未指定迭代器和const_iterator是否是同一類型。


因此VC ++ 2008 Dinkumware實現有問題。


老答案:


你得到了這個錯誤,因為在std lib的某些實現中它set::iterator是相同的set::const_iterator。


例如libstdc ++(隨g ++一起提供)有它(在這里查看整個源代碼):


typedef typename _Rep_type::const_iterator            iterator;

typedef typename _Rep_type::const_iterator            const_iterator;

在SGI的文檔中,它指出:


iterator       Container  Iterator used to iterate through a set.

const_iterator Container  Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)

另一方面,VC ++ 2008 Express編譯你的代碼而不抱怨你在set::iterators 上調用非const方法。


查看完整回答
反對 回復 2019-09-18
  • 3 回答
  • 0 關注
  • 737 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號