重载矩阵模板的+=操作符

C++: overloading the += operator for a matrix template

本文关键字:操作符 重载      更新时间:2023-10-16

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

我要做的是:

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;
     }
}

不管我的错误/业余/冗余编码,:p我主要关心的是如何使用'this'指针,就像我调用' rhs[I][j]一样。因为this->[i][j]和this都不是。[我][j]工作)

我在想也许它会长期工作<<例如:this->operator[] (i)>>,但我不知道如何将双括号合并到其中。或者完全有另一种选择。我希望我解释得很清楚。我感觉答案很简单。我被难住了。如有任何帮助,不胜感激。

谢谢。

你可以写

(*this)[i][j]

或者,如果你想对它极度变态

this->operator[](i)[j];

或者更糟:

this->operator[](i).operator[](j); // :) happy debugging

不要用irregardless这个词。Stewie Griffin说,所有使用这个词和"all of sudden"的人都必须被送到劳改营。

我有一种感觉答案真的很简单

是的,它是:)

(*this)[i][j]