C++ 指向重载索引的箭头 ( this->[ ] )
C++ arrow to overloaded index ( this->[ ] )
我有一个简单的 class,我重载了它的索引运算符:
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]
作为二维数组工作,但数据在内存中是连续的。
但是,从内部成员函数来看,这有点笨拙,我需要做一些像 (*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];
这(双关语)至少与 this->[][] 一样可读。没有?
我有一个简单的 class,我重载了它的索引运算符:
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]
作为二维数组工作,但数据在内存中是连续的。
但是,从内部成员函数来看,这有点笨拙,我需要做一些像 (*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];
这(双关语)至少与 this->[][] 一样可读。没有?