2016-04-24 42 views
-1
Matrix &Matrix::operator*(Matrix &rhs) { 
    if (this->columns != rhs.rows) { 
     this->~Matrix(); 
     return *this; 
    } 
    else { 
     Matrix product(this->rows, rhs.columns); 


     /*for (unsigned int col = 0; col < product.columns; col++) { 
      for (unsigned int row = 0; row < product.rows; row++) { 
       unsigned int val = 0; 
       for (unsigned int i = 0; i < this->columns; i++) { 
        val += this->get(row, i)*rhs.get(i, col); 
       } 
       product.set(row, col, val); 
      } 
     }*/ 

     return product; 
    } 

代碼生成,但運行時崩潰。當調試我得到的錯誤在於拷貝構造函數消息(this->matrix = new double[rows*columns];C++程序成功建立,但在運行時出錯

Matrix::Matrix(const Matrix&m):rows(m.rows),columns(m.columns),matrix(nullptr) { 
    if (!m.isValid()) { 
     return; 
    } 
    this->matrix = new double[rows*columns]; 
    for (unsigned int i = 0; i < rows*columns; i++) { 
     matrix[i] = m.matrix[i]; 
    } 
} 

我不明白爲什麼?複製構造函數正如我在實現*運算符之前那樣工作。我一塊一塊評論一下,發現真正的錯誤,看起來程序因返回產品而崩潰;聲明。這是當我註釋到for循環時,所以這些都不是問題。

我從主要測試很簡單:

#include "Source.h" 
#include "Matrix.h" 
#include<iostream> 

int main() { 
    Matrix A(3,3); 
    Matrix B(3); 
    cout << B << endl; 
    cout << A << endl; 
    Matrix C=A*B; 
    cout << C << endl; 

    return 0; 
} 

我希望有人能幫助我,因爲我真的卡住。 這裏是鏈接到整個程序:

+0

該程序編譯只是意味着它在語法上是有效的。這對於產生你想要的結果沒有任何意義,或者它是否在運行時定義了行爲。只是一個筆記。 –

+0

在您的操作員中返回一個*引用*到一個*本地臨時變量*是無濟於事的。這是UB。 – kfsone

+0

請提供[MCVE]。 'this->〜Matrix();'看起來超級錯誤。 – Barry

回答

2

在你的代碼的operator *方法返回一個局部變量的引用。局部變量product超出範圍並在您return時被銷燬,因此您最終將返回一個懸掛參考,使用該參數可能會導致未定義的行爲。

operator *返回類型也許應該只是Matrix代替Matrix &

Matrix Matrix::operator*(Matrix &rhs) { /* ... your code here ... */ } 
+0

謝謝你,真的很有幫助。這真的很渺茫:/ – user6248314

相關問題