且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++“错误:传递'const std::map<int, std::basic_string<char>>'作为......的“这个"论点

更新时间:2023-11-14 19:35:10

string color::getColorText() const {
    return colors[cColortype];
}

问题是您已将函数标记为 const.std::map 上的 operator[] 被标记为非常量,并且不能在这样的 const 函数中使用.您需要手动使用 std::map::find (或其他机制)搜索输入类型并处理未找到的情况.

The issue is that you've marked the function as const. The operator[] on std::map is marked as non-const, and cannot be used in a const function like this. You need to manually use std::map::find (or other mechanism) to search for the input type and handle the case where it's not found.

如果您使用的是 C++11,则可以改用 std::map::at,它允许在常量映射上使用,如果请求则抛出异常元素不存在.

If you're using C++11, you can instead use std::map::at, which IS allowed to be used on a constant map, and throws an exception if the requested element is not present.