简体   繁体   English

类矩阵加法

[英]Class matrix addition

I have a program that is suppose to add together two matrices but when it gets to the add part in the main it just gets stuck and does nothing. 我有一个程序想将两个矩阵相加,但是当它到达主部分的加法部分时,它只会卡住而无所事事。 I have messed with this for quite some time but to no avail. 我已经花了很长时间弄乱了,但无济于事。 Any help or recommendations would be appreciated. 任何帮助或建议,将不胜感激。

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


}

Your program is violating the rule of big three : it has a destructor but no assignment operator and no copy constructor. 您的程序违反了三大原则 :它有一个析构函数,但没有赋值运算符,也没有复制构造函数。 It keeps the data using raw pointers, but it's not managing proper ownership with copies are done and assignments are performed. 它使用原始指针保留数据,但是它并没有管理适当的所有权,因为副本已经完成,并且执行了赋值。

When your matrix class is copied and assigned your program is entering the Undefined Behavior territory so anything can happen. 复制并分配矩阵类后,程序将进入“未定义行为”区域,因此任何事情都可能发生。 In this code copy construction is done implicitly when passing a matrix parameter by value, and assignment is done explicitly in main . 在此代码中,当按值传递matrix参数时,隐式地完成构造,而赋值则在main显式完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM