samedi 21 septembre 2019

C++ program works as excpected untill I add a destructor to it

#include <iostream>
using namespace std;
class Matrix
{

public:
  long int **Matr;
    long int n;

    void Create()
    {
        Matr = new long int*[n];
        for (int z = 0; z<n; z++)
            Matr[z] = new long int[n];
    }
    // constructors and destructor
    Matrix() :  n(5) { Create(); }

    Matrix(long int i) :  n(i) { Create(); }

  // Copy constructor
  Matrix(Matrix& N)
  {
      n = N.n;

      Matr = new long int*[n];

      for (int i = 0; i < n; i++)
          Matr[i] = new long int[n];

      for (int i = 0; i < n; i++)
      {
          for (int j = 0; j < n; j++)
          {
              Matr[i][j] = N.Matr[i][j];
          }

      }
  }

  Matrix operator *(Matrix &mx)
    {
    int i,j,k,num;
        Matrix result(n);
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                num = 0;
        for (int k = 0; k<n;k++){
          num += Matr[i][k] * mx.Matr[k][j];
        }
        result.Matr[i][j] = num;
    return result;    
    }
  ~Matrix()
    {
        for (int z = 0; z<n; z++){
            delete[] Matr[z];
    }  
        delete[] Matr;
    }

  void Display()
    {
        for (int i = 0; i<n; i++)
        {
            for (int j = 0; j<n; j++)
            {
                cout << Matr[i][j];
            }
            cout << endl;
        }
    }

  Matrix operator +(Matrix &mx)
    {
    Matrix result(n);
        for (int i=0; i < n; i++){
            for (int j=0; j < n; j++){
                result.Matr[i][j] = Matr[i][j] + mx.Matr[i][j];
        //cout << result.Matr[i][j] << "\n";
      }
    }    
    return result;    
    }
};

int main(){
  Matrix M(2);
  M.Matr[0][0] = 0;
  M.Matr[0][1] = 1;
  M.Matr[1][0] = 2;
  M.Matr[1][1] = 3;

  Matrix N(2);
  N.Matr[0][0] = 0;
  N.Matr[0][1] = 1;
  N.Matr[1][0] = 2;
  N.Matr[1][1] = 3;

  Matrix C;


  C= M+N;
  cout << C.Matr[0][0];

  return 0;
}

I am doing a Matrix OOP class with some basic methods. I can't do "+" operator work in the way I want. In this case, when I'm trying to print C.Matr[0][0] it's printing random number for some reason, but if I simply remove destructor from code it works as expected and printing 0. Can someone help me to figure out why this is happening? Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire