main.cpp:
Simple2DMatrix& Simple2DMatrix :: assign(const Simple2DMatrix& matrixB) {
if ((numRows == matrixB.numRows)
&& (numCols == matrixB.numCols)
)
{
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
{
this->setElement(r, c, matrixB.getElement(r, c));
}
}
return (*this);
}
else
{
throw "Dimensions does not match!";
}
}
并添加为:
if ((this->numRows == matrixB.numRows)
&& (this->numCols == matrixB.numCols)
)
{
for (int r = 0; r < this->numRows; r++)
{
for (int c = 0; c < this->numCols; c++)
{
this->setElement(r, c, this->getElement(r, c) + matrixB.getElement(r, c));
}
}
return (*this);
}
else
{
throw " Dimensions does not match!";
}
因此,任务将是: {
if ((numRows == matrixB.numRows)
&& (numCols == matrixB.numCols)
)
{
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
{
this->setElement(r, c, matrixB.getElement(r, c));
}
}
return (*this);
}
else
{
throw "Dimensions does not match!";
}
}
并在operator +的标题中:
Simple2DMatrix<T> matrixTemp(matrixA.numRows, matrixA.numCols);
matrixTemp.sum(matrixA, matrixB);
return (matrixTemp);
并且对于operator =:
this->assign(matrixB);
return(*this);
非常感谢你的所有信息。
答案 0 :(得分:2)
这是你的代码(operator +):
if ((this->numRows == matrixB.numRows)
&& (this->numCols == matrixB.numCols)
)
{
for (int r = 0; r < matrixA.numRows; r++)
{
for (int c = 0; c < matrixA.numCols; c++)
{
this->setElement(r, c, matrixA.getElement(r, c) + matrixB.getElement(r, c));
} //what is matrixA?
}
return (*this); //what you want to return?? it seems you are doing B=B+C
}
else
{
throw " Dimensions does not match!";
}
实际上你需要先创建一个类的临时对象并存储添加的内容 B和C在里面。 然后返回那个临时变量。