代码之家  ›  专栏  ›  技术社区  ›  johnbakers

如何创建访问std::map项的const成员函数

  •  3
  • johnbakers  · 技术社区  · 13 年前

    我只是想返回,而不是改变 std::map 。它有效,但如果我 const 在函数上,我得到了错误 No viable overloaded operator[] for type 'const std::map 。我的代码如下:

    GLuint getCurrentColorAttribute() const {
        return m_programs[m_currentActiveProgram].attributes["SourceColor"];
    }
    

    以下是我的IDE中的错误图像: enter image description here

    1 回复  |  直到 13 年前
        1
  •  5
  •   Tushar    13 年前

    这个 [] 的操作员 std::map 不是 const (因为如果映射中不存在新条目,它可以在映射中创建一个新条目),因此您不能从 常量 作用

    您可以使用 at 而是在 C++11 :

    return m_programs.at(m_currentActiveProgram).attribute["SourceColor"];