C++:为矩阵模板重载+ =运算符

Joe*_*oeC 3 c++ operators matrix

我一直在实现一个自定义模板矩阵类,我有一个功能,我需要一些帮助.我正在尝试重载运算符+ =我使用我已经实现并正在工作的重载运算符[].问题是,我不知道如何将'this'指针与operator []结合起来.

这是我正在尝试做的事情:

Matrix & operator+= (const Matrix & rhs)
{
    if(this->numrows() != rhs.numrows() || this->numcols() != rhs.numrows())
    {
        cout << "ERR0R: Cannot add matrices of different dimensions." << endl;
        return *this;
    }
    else
    {
        theType temp1, temp2, temp3;
        for(int i = 0; i < this->numrows(); i++)
        {
            for(int j = 0; j < this->numcols(); j++)
            {
                temp1 = this->[i][j];
                temp2 = rhs[i][j];
                temp3 = temp1 + temp2;
                this->[i][j] = temp3;
            }
        }
        return *this;
     }
}
Run Code Online (Sandbox Code Playgroud)

无论我的错误/业余/冗余编码如何:P我主要关注的是如何使用'this'指针,就像我称之为"rhs [i] [j]"一样.(既然这不是 - > [i] [j]或者这个.[i] [j]工作)

我想也许它可以用很长的路径<<例如:this-> operator [](i)>>但我无法弄清楚如何将双括号合并到其中.或者也许完全有另一种选择.我希望我能很好地解释自己.我觉得答案很简单.我只是难过.任何帮助表示赞赏.

谢谢.

Arm*_*yan 6

你可以写

(*this)[i][j]
Run Code Online (Sandbox Code Playgroud)

或者,如果你想对它非常歪曲

this->operator[](i)[j];
Run Code Online (Sandbox Code Playgroud)

或者更糟:

this->operator[](i).operator[](j); // :) happy debugging
Run Code Online (Sandbox Code Playgroud)

并且不要使用无所畏惧这个词.Stewie Griffin表示,所有使用该术语并且"突然之间"的人必须被送到工作营 :)