[英]C++: overloading the += operator for a matrix template
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[].
问题是,我不知道如何将'this'指针与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 = 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]." 无论我的错误/业余/冗余编码如何:P我主要关注的是如何使用'this'指针,就像我称之为“rhs [i] [j]”一样。 (Since neither this->[i][j] or this.[i][j] work)
(既然这不是 - > [i] [j]或者这个。[i] [j]工作)
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. 我想也许它可以用很长的路径<<例如:this-> operator [](i)>>但我无法弄清楚如何将双括号纳入其中。 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 :)
Stewie Griffin表示,所有使用该术语并且“突然之间”的人必须被送到工作营 :)
I have a feeling the answer is really simple
我觉得答案很简单
Yes it is :) 是的 :)
(*this)[i][j]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.