2
考慮下面的C++代碼:從STD檢索項::地圖在功能上打上const的
// A.h
class A {
private:
std::map<int, int> m;
int getValue(int key) const;
};
// A.cpp
int A::getValue(int key) const {
// build error:
// No viable overloaded operator[] for type 'const std::map<int, int>'
return m[key];
}
我怎樣才能抓住從m
,使得它在一個const
功能的情況下的價值?
需要注意的是'運營商[]'不'const',因爲如果該鍵不存在,它被添加到具有默認值的地圖。 'operator []'不能是'const',因爲它可以改變'map'。 –