最近编写程序出现了这个错误,很简单的一个程序,在此mark一下。
下面是编译报错程序:
//test.cpp
#include <iostream>
#include <map>
using namespace std;
class Test
{
public:
string &getValue(const int _key) const;
// other function...
private:
map<int, string> m_data;
};
string &Test::getValue(const int _key) const
{
return m_data.find(_key)->second;
}
用g++编译,报如下错误:
$g++ test.cpp
test.cpp: In member function ‘std::string& Test::getValue(int) const’:
test.cpp:18: error: invalid initialization of reference of type ‘std::string&’ from expression
of type ‘const std::basic_string<char, std::char_traits<char>, std::allocator<char> >’
如果我将getValue改成如下的形式:
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& ,进而就报了如上的错误。
改正的方法是:我们也可以像STL中那样,重载两个函数:
const string &getValue(const int _key) const;
string &getValue(const int _key);