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

3

我一直在实现一个自定义的模板矩阵类,我需要帮助的是其中一个函数。我正在尝试重载operator+=,使用已经实现并且运作正常的重载operator[]。问题是,我不知道如何结合'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;
     }
}

无论我的代码有多么错误/业余/冗余,:P 我的主要关注点是如何像调用“rhs [i] [j]”一样使用'this' 指针。(因为既不是this->[i][j]也不是this。[i][j]工作)

我想也许可以用更长的方式 << 例如:this->operator[](i) >> 但我无法想出如何将双括号整合到其中。或者也许有完全不同的替代方案。希望我解释清楚了。我感觉答案非常简单。我只是被难住了。感谢任何帮助。

谢谢。


请查看此链接:http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.10 - Naszta
2个回答

6

非常详尽的回答。正是我所需要的。谢谢! - JoeC

2

我感觉答案非常简单

是的,确实很简单 :)

(*this)[i][j]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接