一个和const有关的编译错误

最近编写程序出现了这个错误,很简单的一个程序,在此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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值