gpt4 book ai didi

c++ - 重载赋值运算符不适用于链接 C++

转载 作者:行者123 更新时间:2023-11-28 02:51:36 28 4
gpt4 key购买 nike

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);

非常感谢您的所有消息。

最佳答案

这是你的(运算符+)代码:

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在里面。然后返回该临时变量。

关于c++ - 重载赋值运算符不适用于链接 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22911412/

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