首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求,请问一个函数重载的有关问题

2012-06-12 
求大虾,请教一个函数重载的问题这是MSDN下map类下的find成员函数的说明,它有两种形式,那我调用的时候到底

求大虾,请教一个函数重载的问题
这是MSDN下map类下的find成员函数的说明,它有两种形式,那我调用的时候到底是调用的哪个如何判断?

是不是这样的:
如何我用map定义的常对象或常引用,则调用第二个find,如何普通定义一个对象或普通引用就调用第一个find?

例如:
定义常对象 const map<string,int> const_map;//const_map为常对象
常引用 void fun(const map<string,int> &const_reference_map)//const_reference_map为常引用

是不是调用他们的find函数就是调用第二个find函数,即常成员函数。
但是谭浩强的书又说了:

23.不要误认为常对象中的成员函数都是常成员函数。常对象只能保证其所有数据成员的值不能被修改。如果在常对象中的成员函数未加const声明,编译系统把它作为非const成员函数处理。


Standard C++ Library Reference 
map::find 

 

Returns an iterator addressing the location of an element in a map that has a key equivalent to a specified key.

 
iterator find(
  const Key& _Key
);
const_iterator find(
  const Key& _Key
) const;
 
这是我的程序里面的一断函数:


void user_query(const map<string,int> &word_map)
{
string search_word;
cout<<"Please enter a word to search(q to quit):";
cin>>search_word;
while(search_word.size() && search_word != "q")
{
map<string,int>::iterator it;
if((it=word_map.find(search_word)) != word_map.end())//这里提示出错
cout<<"Found!"<<it->first<<" occurs"<<it->second<<" times."<<endl;
else
cout<<search_word<<"was not found in text.\n";
cout<<"\nAnother search?(q to quit)";
cin>>search_word;
}
}
错误如下:
>e:\《essential c++》\chap3\chap3_ex3_1_own_08\chap3_ex3_1_own_08\main.cpp(57) : error C2679: 二进制“=”: 没有找到接受“std::_Tree<_Traits>::const_iterator”类型的右操作数的运算符(或没有可接受的转换)
1> with
1> [
1> _Traits=std::_Tmap_traits<std::string,int,std::less<std::string>,std::allocator<std::pair<const std::string,int>>,false>
1> ]


书上答案的迭代指针为常指针,即
map<string,int>::const_iterator it;


求大虾解释下!

[解决办法]
请你把形参的const给去掉吧。编译器认为那是个const变量,你调用find的时候就给调用了const find。导致返回了const_iterator了。还有就是不要轻易的相信书本,特别是中国人编的。要迷信CPU,编译器。

热点排行