gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:06:34 25 4
gpt4 key购买 nike

我一直在实现一个自定义模板矩阵类,我有一个函数需要一些帮助。我正在尝试重载 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 我主要关心的是如何使用“this”指针,就像我调用“rhs[i][j]”一样。 (因为 this->[i][j] 或 this.[i][j] 都不起作用)

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

谢谢。

最佳答案

你可以写

(*this)[i][j]

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

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

或更糟:

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

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

关于C++:为矩阵模板重载 += 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7340927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com