为什么std :: map <int,float>不能使用operator []:错误C2678?

Duc*_*een 1 c++ stl std

有:

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

我正在尝试编译以下内容:

inline float getAreaCost(const int i) const { 
    return m_areaCost[i]; 
}
Run Code Online (Sandbox Code Playgroud)

这导致以下错误:

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

我常想,当我们要求[elementId]我们获得元素值或默认的元素值,所以我不知道怎么能这么简单的情况下,会导致编译错误?

Jos*_*eld 7

据推测,它m_areaCost是该对象getAreaCost的成员.但是,getAreaCost标记为const成员函数.这意味着它不能对成员进行任何修改.所以该m_areaCost成员就是const这个职能部门.

你不能调用operator[]a,const std::map因为它的作用是它插入一个新元素(如果它尚不存在).而是使用std::map::at:

return m_areaCost.at(i);
Run Code Online (Sandbox Code Playgroud)

  • @DuckQueen但是你可以从`const`方法访问它,所以你只能调用它的`const`方法. (3认同)