这个[]运算符是如何重载的?

jin*_*lei 1 c++ class operator-overloading

我正在尝试自己构建一个2D矢量类.

当我在寻找其他人实施的示例代码时,我发现了这个:

class Vector2D {
 public:

  // components
  double x, y;

  Vector2D() : x( 0.0 ), y( 0.0 ) { }

  // returns reference to the specified component (0-based indexing: x, y)
  inline double& operator[] ( const int& index ) {
    return ( &x )[ index ];
  }
}
Run Code Online (Sandbox Code Playgroud)

[]操作员如何超载?我怎么理解(&x)[index]

Lig*_*ica 5

[]操作员如何超载?

厉害.

我怎么理解(&x)[index]

这是一行代码假装我们可以使用指针算法安全地浏览类的成员.我们做不到.代码坏了.

此外,采用intby const引用只是愚蠢的; 基本上没有办法对优化者有用.ints很小,可能甚至小于编译器可能需要"引擎盖下"以实现此引用的指针.