我尝试在VS2010中编译如下代码时,提示错误C2678。
#include <string>
#include <map>
using namespace std;
class test
{
private:
map<string, string> data;
public:
test(){};
~test(){};
public:
const string & get(const string & key)const{return data[key];}; //error C2678
bool set(const string & key, const string & value){data[key]=value;return true;};
};
void main()
{
const string key="Hello world!";
const string value="I'm coming!";
test t;
t.set(key,value);
t.get(key);
}
但是当我把它保留为像这样的函数时
#include <string>
#include <map>
using namespace std;
bool set(const string & key, const string & value, map<string, string> & data)
{
data[key]=value;
return true;
}
const string & get(const string & key, map<string, string> & data)
{
return data[key];
}
void main()
{
const string key="Hello world!";
const string value="I'm coming!";
map<string, string> data;
set(key, value, data);
get(key;
}
它编译并运行。
有人知道问题出在哪里吗?
最佳答案
您已将测试类的 get 成员函数声明为 const。但是 std::map
operator[]
是一个非 const 函数,所以它不能从 const 函数调用。请改用 find
函数。
operator[]
是非 const 的原因是因为如果键不存在,它会将它连同默认构造值一起插入到映射中。
关于c++ - 类中的 map<string, string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8542367/