举例说明,为了这个问题:
void MyClass::MyFunction( int x ) const
{
std::cout << m_map[x] << std::endl
}
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为[]运算符是非const的.
这很不幸,因为[]语法看起来很干净.相反,我必须做这样的事情:
void MyClass::MyFunction( int x ) const
{
MyMap iter = m_map.find(x);
std::cout << iter->second << std::endl
}
Run Code Online (Sandbox Code Playgroud)
这一直困扰着我.为什么[]运算符是非常量的?