error: invalid initialization of reference of type ‘std::string&’ from expression
of type ‘const std::basic_string<char, std::char_traits, std::allocator >’
//main.cpp
#include <iostream>
#include <map>
using namespace std;
class Test
{
public:
string &getValue(const int _key) const;
private:
map<int, string> m_data;
};
string &Test::getValue(const int _key) const
{
return m_data.find(_key)->second;
}
改为以下形式就好了:
const string &getValue(const int _key) const;
//或是:
string &getValue(const int _key);
原因是map的find函数:
iterator find(const key_type& __x)
{ return _M_t.find(__x); }
const_iterator find(const key_type& __x) const
{ return _M_t.find(__x); }
在上面的例子中,getValue是一个const函数,所以其实现调用的是后一个find const函数,其中iterator相当于一个指针,const_iterator有点类似于一个指向常量的指针,所以 m_data.find(_key)->second 返回的 const string& ,进而就报了如上的错误。