开发者

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

开发者 https://www.devze.com 2023-04-03 21:23 出处:网络
I\'ve been implementing a custom template matrix class and I have a function I need some help with. I\'m trying to overload the operator+= for which I use the overloaded operator[] that I have already

I've been implementing a custom template matrix class and I have a function I need some help with. I'm trying to overload the operator+= for which I use the overloaded operator[] that I have already implemented and is working. The problem is, I don't know how to incorporate the 'this' pointer with the operator[].

Here's what I'm trying to do:

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 =开发者_Go百科 0; j < this->numcols(); j++)
            {
                temp1 = this->[i][j];
                temp2 = rhs[i][j];
                temp3 = temp1 + temp2;
                this->[i][j] = temp3;
            }
        }
        return *this;
     }
}

Regardless of my faulty/amateur/redundant coding, :P my main concern is how I can use the 'this' pointer the same way I call "rhs[i][j]." (Since neither this->[i][j] or this.[i][j] work)

I was thinking maybe it would work the long way << for example: this->operator[] (i) >> but I can't figure out how to incorporate the double brackets into that. Or maybe there's another alternative completely. I hope I explained myself well. I have a feeling the answer is really simple. I'm just stumped. Any help is appreciated.

THANKS.


You can write

(*this)[i][j]

or, if you want to be extremely perverted about it

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

or worse:

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

And don't use the word irregardless. Stewie Griffin said everyone who uses that term along with "all of the sudden" must be sent to a work camp :)


I have a feeling the answer is really simple

Yes it is :)

(*this)[i][j]

0

精彩评论

暂无评论...
验证码 换一张
取 消