重载[]操作符并引用对象本身

Overloaded [] operator and referring to the object itself

本文关键字:对象 引用 操作符 重载      更新时间:2023-10-16

我需要在类体内的方法中引用每个顶点。我试过使用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;
  }
}

我如何实现它?

你可以直接写

  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];
}

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

这样使用它
operator[]( i )

this->operator[]( i )

( *this )[i]

直接调用操作符:

operator[](i) += temp;

或通过this:

(*this)[i] += temp;

可以按其名称显式调用重载操作符函数,如下所示:

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

错误:您正在访问类对象而不是成员变量vertices_.

<<p> 修正/strong>:
for(int i = 0; i <= VERTICES_NR; i++)
  vertices_[i] = vertices_[i] + temp;

可以优化为

vertices_[i] += temp;