c++ - 为什么本地图是 const static 时以下内容不起作用

标签 c++ c++11

考虑以下示例:

enum class DOG_TYPE {SHEPHARD, COLLIE,UNKNOWN};

static  const std::map<std::string,DOG_TYPE> dogMap = {
                {"GS",DOG_TYPE::SHEPHARD}
};


DOG_TYPE getDogType(const std::string& dogtype) 
{
    if(dogMap.find(dogtype) != dogMap.end())
    {
        return  dogMap[dogtype];  -->Does not work when std::map is constant
    }
}

int main()
{
DOG_TYPE j = getDogType("GS");
std::cout << int(j);
}

在上面的例子中,语句return dogMap[dogtype];返回错误

error: passing 'const std::map<std::__cxx11::basic_string<char>, DOG_TYPE>' as 'this' argument discards qualifiers [-fpermissive]
         return  dogMap[dogtype];

我想知道为什么会这样,为什么 map 不能是 const static

最佳答案

std::map 上使用 operator[] 创建对象(如果对象不存在)。所以这是一个只能在你被允许修改的 map 上执行的操作。使用 find相反。

关于c++ - 为什么本地图是 const static 时以下内容不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779259/

相关文章:

来自 C++ 的 C# 回调提供访问冲突

c++ - 对于简单的矩阵乘法,OpenCL CPU 比 OpenCL GPU 更快

c++ - 用作 std::multimap 删除范围的第一个和最后一个的递增迭代器

c++ - 具有函数、输入和输出类型的可变参数模板

c++ - 为什么类持有可复制的引用?

c++ - 密文长度不是 cryptopp 中 block 大小的倍数

c++ - 无法使用 sqlite3 和 C++ 解压缩从 sql 表中选择的压缩字符串

c++ - 如何使 QGraphicsItem 的位置依赖于另一个 QGraphicsItem?

c++ - 我如何 move std::unique_ptr 作为构造函数参数?

C++、循环依赖、模板和用户类型