[]下标的意义
数组:
int array[10];
array[0]获取的是值,还是引用?
std::map<int,string> m_map;
m_map[0]返回的是引用还是值,还是指针。
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>class Test{
public:std::string get_name(int id) const{if (m_map.contains(id)) {return m_map[id];} else {return std::string();}}
private:std::map<int,std::string> m_map{{0,"zero"},{1,"one"}};
};
int main() {Test t;std::cout<<t.get_name(0)<<std::endl;return 0;
}
报错的原因:
函数是const类型,而m_map[id]返回的是引用。
c++编译器为了防止对返回对象的修改,const限定的成员函数内不允许返回引用类型,所以报错。
怎么返回值
map---at()函数