来, 看程序:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class A
{
public:
map<string, string> m_map;
};
void test(const A &a)
{
string s = a.m_map["hello"];
cout << s << endl;
}
int main()
{
A a;
a.m_map["hello"] = "world";
test(a);
return 0;
}
g++编译错误如下:
main.cpp: In function ‘void test(const A&)’:
main.cpp:14: error: passing ‘const std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >]’ discards qualifiers
原因: 在test中, a的值不能变, 而a.m_map["hello"]是一个可读写操作, 所以有问题。 还是用const_iterator吧, 先查找"hello", 再访问it->second