【问题标题】:Operator+ not returning what i expect c++运算符+没有返回我期望的c++
【发布时间】:2013-10-22 05:29:16
【问题描述】:
matrixType& matrixType::operator+(const matrixType& matrixRight)
{
    matrixType temp;
    if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize)
    {
        temp.setRowsColumns(rowSize, columnSize);
        for (int i=0;i<rowSize;i++)
        {
            for (int j=0;j<columnSize;j++)
            {   
                temp.matrix[i][j] = matrix[i][j] + matrixRight.matrix[i][j];
            }
        }
    }
    else
    {
        cout << "Cannot add matricies that are different sizes." << endl;
    }
    cout << temp;
    return temp;
}


最后的 cout 打印出我所期望的但是当我在我的 main 中将矩阵 a 和矩阵 b 一起添加时没有输出我不明白为什么在我返回它之前它会正确但它没有当它返回时做任何事情。

int main()
{
    matrixType a(2,2);
    matrixType b(2,2);
    matrixType c;
    cout << "fill matrix a:"<< endl;;
    a.fillMatrix();
    cout << "fill matrix b:"<< endl;;
    b.fillMatrix();

    cout << a;
    cout << b;

    cout <<"matrix a + matrix b =" << a+b;

    system("PAUSE");
    return 0;
}

cout a 打印出矩阵 a 正确且与 b 相同,但 a+b 不打印任何内容,尽管在上面的运算符重载中我将其打印出来并且打印出正确。

【问题讨论】:

    标签: c++ operator-keyword


    【解决方案1】:

    您正在返回对临时的引用,从而导致未定义的行为operator+ 应该返回一个值:

    matrixType operator+(const matrixType& matrixRight);
    

    【讨论】:

    • 虽然这绝对正确,但对于矩阵类型,如果返回值优化关闭或不起作用,这可能会变得昂贵。对于这种重量级的数据结构,使用其他成员函数或 operator+= 可能是个好主意。
    • @arne 我希望 NRVO 能够工作,但它有助于使类型在不能移动的情况下有效地移动。尽管如此,在涉及许多临时对象的表达式中可能存在问题,在这种情况下,一些模板表达式魔术是一个很好的解决方案。我不确定如何从成员函数或operator+= 中获得Matrix a = b + c; 类型的表达式。
    • @juanchopanza 你说得对,最后一种表达方式用operator+=不太好,但是可以写成Matrix a = b; a += c。我只看到大量临时变量的问题,可能在涉及乘法、求逆等的复杂方程中。您可以轻松编写成员函数,如 add(Matrix const &amp;summand, Matrix &amp;result) 以避免复制。
    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 2021-05-30
    • 1970-01-01
    • 2021-12-11
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多