索引运算符constness

veh*_*zzz 1 c++

为什么我们需要两个?在哪种情况下调用以下每个operator []?

  class X {
      public:
        //...
        int &operator [](int index);
        const int &operator [](int index) const;
    };
Run Code Online (Sandbox Code Playgroud)

Phi*_*gan 5

foo( X x )
{
  x[0];  // non-const indexer is called
}

bar ( const X x )
{
  x[0]; //const indexer is called
}
Run Code Online (Sandbox Code Playgroud)