class CityTimeStampManager
{
public:
typedef std::string key_type;
typedef int value_type;
typedef std::map<key_type, value_type> MapType;
typedef MapType::const_iterator ConstIterType;
CityTimeStampManager(const char* filename);
~CityTimeStampManager() { cityTimeStampTable.clear(); }
int getTimeStamp(const key_type& key) const
{
if (cityTimeStampTable.find(key) == cityTimeStampTable.end())
{
return -1;
}
return cityTimeStampTable[key];
}
private:
std::string file_name;
MapType cityTimeStampTable;
};
cityTimeStamp是一个map结构,getTimeStampV1是根据key做一次查询,加了const,结果编译报错:
1>e:\spliteblock\dc3\datamanager.h(44) : error C2678: 二进制“[”: 没有找到接受“const CityTimeStampManager::MapType”类型的左操作数的运算符(或没有可接受的转换)
1> c:\program files\microsoft visual studio 9.0\vc\include\map(167): 可能是“int &std::map<_Kty,_Ty>::operator [](const std::basic_string<_Elem,_Traits,_Ax> &)”
1> with
1> [
1> _Kty=CityTimeStampManager::key_type,
1> _Ty=CityTimeStampManager::value_type,
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1> 试图匹配参数列表“(const CityTimeStampManager::MapType, const CityTimeStampManager::key_type)”时
模板的错误提示确实晕,双击跳到map的operator[]定义:
mapped_type& operator[](const key_type& _Keyval)
{ // find element matching _Keyval or insert with default mapped
iterator _Where = this->lower_bound(_Keyval);
if (_Where == this->end()
|| this->comp(_Keyval, this->_Key(_Where._Mynode())))
_Where = this->insert(_Where,
value_type(_Keyval, mapped_type()));
return ((*_Where).second);
}
};
operator[]返回的是mapped_type引用,与const成员函数思路不一致。return cityTimeStampTable[ key ]返回的是引用,去掉成员函数的const则编译通过。
后者重写下类成员函数,使用map的const_iterator:
int getTimeStamp(const key_type& key) const
{
typedef std::map<key_type, value_type> MapType;
typedef MapType::const_iterator ConstIterType;
ConstIterType iter = cityTimeStampTable.find(key);
if (iter == cityTimeStampTable.end())
{
return -1;
}
return (*iter).second;
// return cityTimeStampTable[key];
}
const的连锁反应,好久不写C++ code了,备忘一下。