簡體   English   中英

C++ 錯誤:傳遞&#39;const umap_int {aka const std::unordered_map<int, int> }&#39; 作為 &#39;this&#39; 參數丟棄限定符 [-fpermissive]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM