重载 [] 运算符并引用对象本身

Overloaded [] operator and referring to the object itself

我需要引用 class 主体内的方法中的每个顶点。我试过使用 this->Solid:: 等,但效果也不理想。

无论如何,我已经把其他所有东西都超载了,但我无法弄清楚,也无法在网络上的任何地方搜索它。

#define VERTICES_NR 8

class Solid {
protected:
  Vector _vertices[VERTICES_NR];

// ... some other code (does not matter) ... //


public:
  void Solid::Move()
  {
    Vector temp; // <- my own standalone type.

    cout << "How would you like to move the solid. Type like \"x y z\"" << endl;
    cin >> temp;

    for(int i = 0; i <= VERTICES_NR; i++)
      this->[i] = this->[i] + temp;
  }
}

我该如何实施?

重载的运算符函数可以通过其名称显式调用,如下所示:

operator[](i) = operator[](i) + temp;

你可以简单地写

  for(int i = 0; i < VERTICES_NR; i++)
                  ^^^
    _vertices[i] += temp;

如果你想定义下标运算符那么它可以像

Vector & operator []( int n )
{
    return  _vertices[i];
}

const Vector & operator []( int n ) const
{
    return  _vertices[i];
}

在这种情况下,在 class 定义中,您可以像

一样使用它
operator[]( i )

this->operator[]( i )

( *this )[i]

要么直接打电话给接线员:

operator[](i) += temp;

或通过this:

(*this)[i] += temp;

错误:您访问的是class对象而不是成员变量vertices_。

更正:

for(int i = 0; i <= VERTICES_NR; i++)
  vertices_[i] = vertices_[i] + temp;

可以优化为

vertices_[i] += temp;