Good day! I thought to overload in this way, but this code does not work. Tell me how to fix it?

friend istream& operator >> (istream &in, Matrix &mas) { for (int i = 0; i < mas.n; i++) { for (int j = 0; j < mas.m; j++) { in >> mas.mas[i][j]; } } return in; } 

Created a class

 class Matrix {private: int n, m, **mas; public: Matrix (int n, int m) { int**mas = new int*[n]; for (int i = 0; i < n; i++) { mas[i] = new int[m]; } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) mas[i][j] = 0; } 
  • 3
    And what does "not working" mean? - Harry
  • @Harry The program does not respond when I try to use this operator - choko
  • And how should she respond? Do you enter the required data? Give a minimal example, pls ... - Harry
  • What is "not responding in any way"? And in the above code, you are never trying to "use this operator." - AnT
  • @Harry added the code - choko

1 answer 1

Your constructor does not initialize the n and m fields of your class. All the work in your constructor is done with local parameters n and m , while nobody remembers the class fields ( this->n and this->m ). In them as there was garbage from the very beginning, it remains so. Most likely you are just “lucky” and in these fields there are zeros or some kind of negative “junk” values. As a result, it turned out that the cycles in your operator do not want to do any iteration, i.e. The program "does not react at all" to your operator.

And you make the formation of the matrix itself in some local variable mas instead of the field of the class mas . Why did you set this local variable in the constructor? If you like working with the mas local variable first, then do not forget to end up storing it in the field of this->mas class.

In other words, as an option to fix the constructor code: add initialization of the class fields to the constructor and remove this local variable mas

 Matrix (int n, int m) : n(n), m(m) { mas = new int*[n]; ...