映射<字符串,字符串>在类中

map<string, string> in class

本文关键字:字符串 映射 lt gt      更新时间:2023-10-16

当我尝试在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的原因是因为如果键不存在,那么它将它与默认构造值一起插入到映射中。

要在const映射中查找对象,需要使用find成员函数,不能使用operator[]:

    const string & get(const string & key)const {return data.find(key)->second;}