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

标签 c++ operator-overloading

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/

相关文章:

C++ 多态性 : going from base class to derived class

c++ - 构造一个包含二进制数组的 hexValue 的字符串

c++ - 为什么插入运算符打印地址而不是字符串?

c++ - operator= 在 C++ 中重载

c++ - 如何处理黑莓10中自定义控件的触摸事件

c++ - 在派生对象上 move 构造函数

c++ - 我无法在 Code::blocks IDE 上运行此代码,但可以在网上正常运行...!! 谁能告诉我应该进行哪些修改才能使其在 IDE 上运行?

c++ - 错误:return type specified for 'operator std::string {aka std::__cxx11::basic_string<char>}'

c++ - (++i) 和 (i++) 的区别

c++ - 运算符重载 [][] 二维数组 C++