模板中const导致的编译错误

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了,备忘一下。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值