类矩阵加法

时间:2013-10-06 22:16:22

标签: c++ class matrix addition

我有一个程序,假设将两个矩阵加在一起,但当它到达主要的添加部分时,它就会卡住并且什么都不做。我已经搞砸了很长一段时间,但无济于事。任何帮助或建议将不胜感激。

#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();


}

1 个答案:

答案 0 :(得分:0)

您的程序违反了rule of big three:它有一个析构函数,但没有赋值运算符,也没有复制构造函数。它使用原始指针保存数据,但它不能管理正确的所有权,副本完成并执行分配。

当您的矩阵类被复制并分配时,您的程序正在进入未定义的行为区域,因此任何事情都可能发生。在此代码中,按值传递matrix参数时隐式执行复制构造,并在main中明确完成赋值。