2013-10-22 30 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