C++指向重载索引的箭头 ( this->[ ] )

C++ arrow to overloaded index ( this->[ ] )

本文关键字:gt this- 重载 索引 C++      更新时间:2023-10-16

我有一个简单的类,我重载了它的索引运算符:

class dgrid{
    double* data; // 1D Array holds 2D data in row-major format
  public:
    const int nx;
    const int ny;
    double* operator[] (const int index) {return &(data[index*nx]);}
}

通过这种方式,dgrid[x][y]作为一个2d数组工作,但数据在内存中是连续的。

然而,从内部成员函数来看,这有点笨拙,我需要做一些像(*this)[x][y]这样的事情,它可以工作,但看起来很臭,尤其是当我有这样的部分时:

(*this)[i][j] =   (*this)[i+1][j]
                + (*this)[i-1][j]
                + (*this)[i][j+1]
                + (*this)[i][j-1] 
                - 4*(*this)[i][j];

有更好的方法吗?类似this->[x][y]的东西(但这不起作用)。使用一个小函数f(x,y) returns &data[index*nx+ny]是唯一的选择吗?

您可以重载->,但为什么不简单地执行:

T& that = *this; //or use auto as t.c. suggests
that[i][j] =  that[i+1][j]
            + that[i-1][j]
            + that[i][j+1]
            + that[i][j-1] 
            - 4*that[i][j];

这(双关语)至少和这个一样可读——>[][]。不