2013-10-22 27 views
0
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我期望,但是当我在我的主要添加矩阵和矩阵B一起没有输出,我不明白为什么它在我返回它之前会在线上,但它在返回时不会做任何事情。运营商+不返回我的期望C++

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一个打印出所述基质中的正确的同对于b,但A + B犯规打印任何虽然在运算符重载上述我打印出来,它打印出正确的。

回答

2

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

matrixType operator+(const matrixType& matrixRight); 
+0

THANK YOU !!!!!!!!!!!!!!!!!!!!! – CrimOudin

+0

虽然这是绝对正确的,但对于矩阵类型,如果返回值优化关闭或不起作用,则这可能会变得昂贵。对于这种重量级的数据结构,使用其他成员函数或operator + =可能是一个好主意。 – arne

+0

@arne我期望NRVO能够工作,但它有助于在没有的情况下高效地移动类型。尽管如此,在涉及许多临时表达式的表达式中可能存在问题,在这种情况下,一些模板表达式魔法是一个很好的解决方案我不知道如何从成员函数或'operator + ='中获得'Matrix a = b + c;'类型的表达式。 – juanchopanza