C++指向重载索引的箭头 ( this->[ ] )
C++ arrow to overloaded index ( this->[ ] )
我有一个简单的类,我重载了它的索引运算符:
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];
这(双关语)至少和这个一样可读——>[][]。不
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- EASTL矢量<向量<int>>连续的
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- QObject::连接无法将信号连接到*this*对象的插槽
- 析构函数中的"delete this"
- 为什么成员函数内的"this"指针为空?
- 为什么我需要在转换构造函数上引用 this->?
- "this"指针的值在对象的生存期内是否恒定?
- ``这个''不能用this-&gt;指针变量