【问题标题】:Class matrix addition类矩阵加法
【发布时间】:2013-10-06 22:16:22
【问题描述】:

我有一个程序,它假设将两个矩阵相加,但是当它到达 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();


}

【问题讨论】:

    标签: c++ class matrix addition


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 2016-08-03
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多