c ++ STL map.find()或map.operator []不能在具有const限定符的类成员函数中使用

Mer*_* Xu 3 c++ stl const map member

我对以下代码感到困惑,为什么它无法成功编译?

class Test { 
public:
  int GetValue( int key ) const
  {
      return testMap[key];
  }

  map<const int, const int> testMap; 
};
Run Code Online (Sandbox Code Playgroud)

始终存在编译错误:

error C2678: binary '[': no ??operator found which takes "const std :: map <_Kty,_Ty>" type of the left operand operator (or there is no acceptable conversion).
Run Code Online (Sandbox Code Playgroud)

我试图将const限定符放在任何地方,但它仍然无法通过.你能告诉我为什么吗?

jua*_*nza 6

operator[]不是const,因为它插入一个元素,如果一个元素与给定的密钥不存在.find()确实有一个const重载,所以你可以const实例或const引用或指针调用它.

在C++ 11中,std::map::at()如果没有给定键的元素,则会添加边界检查并引发异常.所以你可以说

class Test { 
public:
  int GetValue( int key ) const
  {
      return testMap.at(key);
  }

  std::map<const int, const int> testMap; 
};
Run Code Online (Sandbox Code Playgroud)

否则,使用find():

  int GetValue( int key ) const
  {
    auto it = testMap.find(key);
    if (it != testMap.end()) {
      return it->second;
    } else {
      // key not found, do something about it
    }
  }
Run Code Online (Sandbox Code Playgroud)