举个人为的例子,为了回答这个问题:
void MyClass::MyFunction( int x ) const
{
std::cout << m_map[x] << std::endl
}
由于[]操作符是非 const 的,因此无法编译。
这很不幸,因为[]语法看起来非常干净:
void MyClass::MyFunction( int x ) const
{
MyMap iter = m_map.find(x);
std::cout << iter->second << std::endl
}
这一直困扰着我,为什么[]操作符是非常数的?