faf*_*afa 11 c++ indexing brackets operator-overloading
我正在用c ++编写一个矩阵类,并尝试重载一些像=和>>和<<等的运算符.
我无法为矩阵类重载operator [] [].如果我有像M1这样的类矩阵的对象,那么我可以用这种方式为每个元素赋值:
M1[1][2]=5;
Run Code Online (Sandbox Code Playgroud)
要么
int X;
X=M1[4][5];
Run Code Online (Sandbox Code Playgroud)
Ale*_*ler 19
只是重载operator[]并使其返回指向矩阵的相应行或列的指针.由于指针支持下标[],因此可以通过"双方"表示法[][]进行访问.
您还可以operator()使用两个参数重载.
你可以超载operator[]。因此,如果您想以这种方式使用矩阵,则应该将矩阵设为向量数组。
class Matrix
{
...
Vector & operator[]( int index );
...
};
Run Code Online (Sandbox Code Playgroud)
和
class Vector
{
...
double & operator[]( int index );
...
};
Run Code Online (Sandbox Code Playgroud)
最后:
Matrix m;
...
double value = m[i][j];
...
Run Code Online (Sandbox Code Playgroud)
没有operator[][],您可以实现operator[]返回对行/列对象的引用,其中您可以实现operator[]返回单元格引用。
您可以执行以下操作来避免所有麻烦。
struct loc
{
int x;
int y;
};
Run Code Online (Sandbox Code Playgroud)
然后在你的operator[]超载中,接受一个loc类似的东西
T& operator[](loc const& cLoc)
{
// now you have x/y you can return the object there.
}
Run Code Online (Sandbox Code Playgroud)
要调用,您只需执行以下操作:
matrix[loc(2,3)] = 5;
Run Code Online (Sandbox Code Playgroud)