1

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

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


}
4

1 回答 1

0

你的程序违反了三巨头的规则:它有一个析构函数,但没有赋值运算符,也没有复制构造函数。它使用原始指针保存数据,但它没有通过完成副本和执行分配来管理适当的所有权。

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

于 2013-10-06T22:20:48.967 回答