c++ - 类中的 map<string, string>

标签 c++ visual-studio-2010 templates stl dictionary

我尝试在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/

相关文章:

c++ - 使用 SOIL 在 openGL 中显示图像

java - 从 Struts2 应用程序中的 FreeMarker 获取模板文本

arrays - 带有 JSON 数据并访问数组和对象的 Handlebars 模板

以对象指针为参数的 C++ 复制构造函数

c++ - SFML2 与每个对象的碰撞

c++ - 如何在 C++ 中使用 remove 命令删除句子中的空格?

c++ - "detail"和 "impl"文件夹有什么用?

c++ - *1.0 在这段代码中做了什么?

asp.net - 如何使用Visual Studio内置的SQL Server?

jquery - 在页面上存储 HTML 模板的最佳实践?