2013-10-06 61 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中明确完成分配。