2013-10-06 60 views
1

我有一個程序,它假設將兩個矩陣加在一起,但是當它到達主體中的加法部分時,它只會卡住,什麼也不做。我已經搞砸了很長一段時間,但無濟於事。任何幫助或建議,將不勝感激。類矩陣加法

#include <iostream> 
using namespace std; 

class matrix 
{ 
private: 
    int **p, m, n; 
public: 
    matrix(int row, int col) 
{ 
    m = row; 
    n = col; 
    p = new int*[m]; 
    for (int i = 0; i < m; i++) 
p[i] = new int[n]; 
} 
~matrix() 
{ 
    for (int i = 0; i < m; i++) 
delete p[i]; 
    delete p; 
} 
void fill() 
{ 
    cout<<"Enter the matrix elements:"; 
    for(int i = 0; i < m; i++) 
    { 
for(int j = 0; j < n; j++) 
{ 
    cin >> p[i][j]; 
} 
    } 
} 
void display() 
{ 
    cout <<"The matrix is:"; 
    for(int i = 0; i < m; i++) 
    { 
    cout << endl; 
    for(int j = 0; j < n; j++) 
    { 
    cout << p[i][j] <<" "; 
    } 
    } 
    cout << endl; 
} 
matrix operator +(matrix m2) 
{ 
    matrix T(m, n); 
    for(int i = 0; i < m; i++) 
    { 
    for(int j = 0; j < n; j++) 
    { 
    T.p[i][j] = p[i][j] + m2.p[i][j]; 
    } 
    } 
    return T; 
} 

matrix operator =(matrix eq) 
{ 
    m = eq.m; 
    n = eq.n; 
    p = eq.p; 

    return *this; 
} 

friend matrix operator *(matrix, matrix); 
}; 

matrix operator *(matrix a , matrix b) 
{ 
    matrix B(1,1); 
    if(a.n == b.m) 
    { 
     matrix T(a.m, b.n); 
     for(int i = 0; i < a.m; i++) 
     { 
    for(int k = 0; k < b.n; k++) 
    { 
    T.p[i][k] = 0; 
    for(int j = 0; j < a.n; j++) 
    { 
     T.p[i][k]+= a.p[i][j] * b.p[j][k]; 
    } 
} 
    } 
    B = T; 
    } 
    return B; 
} 

int main() 
{ 

    matrix a(3,3), b(3,3); 

    a.fill(); 
    a.display(); 

    b.fill(); 
    b.display(); 

    cout << "addition of a and b\n"; 
    b = b + a; 
    b.display(); 

    cout << "multiplication of a and b\n"; 
    b = (a * b); 
    b.display(); 


} 

回答

0

你的程序違反了rule of big three:它有一個析構函數,但沒有賦值運算符,沒有拷貝構造函數。它使用原始指針來保存數據,但它沒有管理正確的所有權,並且完成了副本並執行了分配。

當您的矩陣類被複制並分配您的程序正在進入未定義的行爲領土,因此可能發生任何事情。在此代碼中,按值傳遞matrix參數時隱式完成複製構造,並且在main中明確完成分配。