一个和const有关的编译错误
来源:互联网 发布:ipadair2无法下载软件 编辑:程序博客网 时间:2024/05/21 19:20
最近编写程序出现了这个错误,很简单的一个程序,在此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);
- 一个和const有关的编译错误
- 有关const的一个误区
- 有关指针的一个错误
- 一个有关ParametersInterceptor 的错误
- 有关popupWindow的一个错误
- 一个有关callout的错误
- 有关编译嵌入式android的swap空间不够导致的编译错误和解决办法
- 有关 指针和const
- 模板中const导致的编译错误
- 有关webkit编译遇到的一些错误
- 与namespace有关的两个编译错误
- 有关const的点点滴滴
- 一个有关全局变量引发的错误。
- 有关ajax的一个小错误
- python中有关类的一个错误
- Maven使用FAQ:与Maven版本和字符集编码有关的编译错误处理
- 一个恼人的编译错误......
- 一个与map下标操作有关的编译错误(花了5分钟才找到原因)
- 各种浏览器js调试
- 回顾我在中兴通讯的五年(一)
- MyEclipse10安装aptana插件,以及安装后出现问题的解决方法
- 面试题目(.net)
- 对VC的链接过程讲的最NB的文章
- 一个和const有关的编译错误
- Remove Duplicates from Sorted List
- xcode4发布测试-打包(Archive)
- JAVA开源解析HTML工具
- (转载)cocos2d-X学习之主要类介绍:节点CCNode
- usb
- 7.3.1: 理解依赖注入
- netstat -ano|findstr 5037
- CentOS之SSH安装与配置