[英]C++ Error: “expression must have integral or unscoped enum type” when inserting element into std::map with operator[]
這個標題有很多問題,但似乎它們都不與我的情況相似。
我有一個班級成員
std::map<std::string, Mode> m_stringToMode;
Mode
是
enum class Mode
{
Default, Express
};
還有一個const
方法,其中我已使用operator[]
將新元素插入到地圖中
void LevelParser::myFunc() const
{
std::string myStr = "myStr";
m_stringToMode[myStr] = Mode::Express;
}
我有兩個錯誤
C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<std::string,Mode,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
C++ Error: “expression must have integral or unscoped enum type”
經過一段時間的調試,我發現我在嘗試修改const成員函數中的成員變量時做了愚蠢的事情。
所以我的問題是。 我收到的錯誤消息與我所做的錯誤有什么聯系嗎? 為什么在這種情況下編譯器會出現此錯誤?
我正在Visual Studio 2013上編譯我的代碼
第一個錯誤的原因很明確:在const
限定成員函數內,通過const
限定訪問路徑訪問對象的所有非mutable
數據成員。 因此,您的映射實際上是const
並且您正在嘗試在其上調用非const
函數。
至於第一個錯誤的確切措辭:請記住, std::map::operator[]
與其他函數幾乎一樣。 您使用類型為const std::map
和std::string
參數來調用它。 編譯器說找不到任何可以接受它們的重載。 當然,原因是僅有的重載需要一個非const
map
。
您遇到的第二個錯誤可以簡單地忽略。 編譯器對第一個錯誤有些困惑,並打印出虛假的第二個錯誤。
可能發生的情況是編譯器說“您不能在這里使用map
的operator []
,它是非const
而您的映射是const
。” 然后,由於找不到[]
的運算符重載,因此將其解釋為內置運算符[]
,對此至少一個操作數必須具有整數或無作用域枚舉類型。 因此,第二個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.