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

Sam*_*dis 6 c++ operator-overloading

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

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]);}
}
Run Code Online (Sandbox Code Playgroud)

这种方式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];
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?像this->[x][y](但这不起作用).使用一点功能f(x,y) returns &data[index*nx+ny]是唯一的选择吗?

Jef*_*ica 5

你可以重载 - >,但为什么不简单地做:

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];
Run Code Online (Sandbox Code Playgroud)

那个(双关语)至少和这个一样可读 - > [] [].不是吗?