[英]strange const correctness error
我有一個包含類的頭文件。 在那個類中,我有一個像這樣的函數:
class Definition
{
public:
int GetID()
{
return Id;
}
//Other methods/variables
private:
int Id;
}
當我嘗試獲取該ID時:
for (std::map<Definition, std::vector<bool> >::iterator mapit = DefUseMap.begin(); mapit != DefUseMap.end(); ++mapit, defIndex++)
{
stream << "Definition " << (*mapit).first.GetID() << " Def Use" << endl << "\t";
}
我收到以下錯誤
CFG.cc:1145:錯誤:將'const Definition'作為'int Definition :: GetID()'的'this'參數傳遞,丟棄限定符
是因為我在地圖中使用了定義,而且我不允許在該映射定義上調用方法? 有沒有辦法讓ID變量出來?
提前致謝
聲明getID()
方法const:
int getId() const
{
return Id;
}
然后可以通過const引用調用該方法,這是傳遞operator<<()
方法。
map<Key, Value>
將您的數據內部存儲在std::pair<const Key, Value>
。 這樣就很難意外地改變Key並破壞元素的排序。
為了能夠為const鍵調用GetID(),該函數也必須被聲明為const:
int GetID() const;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.