拥有:
std::map<const int, float> m_areaCost;
我正在尝试编译以下内容:
inline float getAreaCost(const int i) const {
return m_areaCost[i];
}
这会导致以下错误:
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)
我曾经认为当我们调用 [elementId]
时我们得到的是元素值或默认元素值,所以我想知道这种简单的情况怎么会导致编译错误?
最佳答案
大概 m_areaCost
是 getAreaCost
所属对象的成员。但是,getAreaCost
被标记为 const
成员函数。这意味着它不能对成员进行任何修改。所以m_areaCost
成员在这个函数中是const
。
您不能在 const std::map
上调用 operator[]
,因为它的效果是插入一个新元素(如果它尚不存在)。而是使用 std::map::at
:
return m_areaCost.at(i);
关于c++ - 为什么 std::map<int, float> 不能使用 operator[]: error C2678?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15614735/