【问题标题】:C++: overloading the += operator for a matrix templateC++:为矩阵模板重载 += 运算符
【发布时间】:2011-09-07 21:50:42
【问题描述】:

我一直在实现一个自定义模板矩阵类,我有一个需要帮助的函数。我正在尝试重载 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] 都不起作用)

我在想也许它会长期有效operator[] (i) >> 但我不知道如何将双括号合并到其中。或者也许完全有另一种选择。我希望我能很好地解释自己。我感觉答案很简单。我只是难过。任何帮助表示赞赏。

谢谢。

【问题讨论】:

标签: c++ matrix operators


【解决方案1】:

你可以写

(*this)[i][j]

或者,如果你想变得非常变态

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

或更糟:

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

并且不要使用“不顾一切”这个词。 Stewie Griffin said everyone who uses that term along with "all of the sudden" must be sent to a work camp :)

【讨论】:

  • 非常彻底的答案。正是我需要的。谢谢!
【解决方案2】:

我感觉答案很简单

是的:)

(*this)[i][j]

【讨论】:

    猜你喜欢
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多