![](/img/trans.png)
[英]error: passing ‘const std::unordered_map<char, int>’ as ‘this’ argument discards qualifiers
[英]C++ error: passing ‘const umap_int {aka const std::unordered_map<int, int>}’ as ‘this’ argument discards qualifiers [-fpermissive]
我正在嘗試通過 unordered_map 的映射值的方法獲取常量引用。 unordered_map 是一個類成員。 但是,下面的代碼不起作用並引發標題中所述的錯誤。
我試圖將const umap_int::mapped_type &
更改為const int &
,這也不起作用。 返回對簡單數據類型(int、double、...)變量的 const 引用的標准示例有效。
#include <unordered_map>
using namespace std;
typedef unordered_map<int, int> umap_int;
class class_A{
public:
class_A(){
for(int k=0; k<3;++k)
M[k] = k;
}
const umap_int::mapped_type & get_M(int key) const{
return M[key];
}
private:
umap_int M;
};
int main(){
class_A A;
return 0;
}
在 const 方法中,您只能調用M
的 const 成員函數。 unordered_map::operator[]
重載都是非常量引用。 所以你不能在 const get_M
使用它。 您可以從get_M
簽名中刪除const限定符,或使用具有 const 重載的find
,但隨后您需要處理傳遞的鍵不存在映射值的情況:
const umap_int::mapped_type & get_M(int key) const {
//return M[key];
auto it = M.find(key);
if (it != M.end())
return it->second;
// do sth here ...
// throw exception
// make static variable with default value which will be accessed
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.