Please tell me where my mistake is. I implemented a class with a two-dimensional dynamic array. The number of columns and fields is set through the constructor. The problem occurs when I try to overload the input operator in a similar way:

friend IntArr& operator >> (istream &in, IntArr& a) { for (int i = 0; i < a.rows; i++) { for (int j = 0; j < a.cols; j++) { in >> a.pa[i][j]; } } return in; } 

Here is the class itself:

 class IntArr { friend IntArr& operator >> (istream &in, IntArr& a) { for (int i = 0; i < a.rows; i++) { for (int j = 0; j < a.cols; j++) { in >> a.pa[i][j]; } } return in; } private: int **pa; int rows, cols; public: IntArr() { pa = 0; rows = 0; cols = 0; } IntArr(int rows, int cols) { this->rows = rows; this->cols = cols; float **pa = new float*[this->rows]; // две строки for (int count = 0; count < 2; count++) pa[count] = new float[this->cols]; // и пять столбцов } }; 
  • "The problem arises ..." What is the problem ??? In the above code, almost everything is done correctly, except for the strange number 2 in the memory allocation cycle. Where did the 2 come from? The commentary says "two lines and five columns." Where did "two rows and five columns" suddenly come from if you were given variable numbers of rows and columns? - AnT

2 answers 2

In C ++, there are only one-dimensional arrays, and pa is a pointer to an array with pointers. In the IntArr constructor IntArr you declare a local variable float **pa , with the same name as the class field, all fields of the class remain uninitialized. It must be something like this (omitting the questions of the subsequent release of memory):

 private: int ** m_pa; private: int m_rows; private: int m_cols; public: explicit IntArr(void): m_pa{}, m_rows{}, m_cols{} {} public: explicit IntArr(int rows, int cols): m_pa{new float *[rows]}, m_rows{rows}, m_cols{cols} { for (int row_index{0}; row_index < rows; ++row_index) { m_pa[row_index] = new float[cols]; } } 
  • Your posts are a little incomprehensible. Do you use new language standards? - I. Bilous 2:01 pm
  • @ I.Bilous No, everything is in C ++ 11. And if you do not use list initialization, then in the framework of C ++ 03. - VTT
  • Okay thank you. I just see such records for the first time. Now I will understand) - I. Bilous
  friend IntArr& operator >> (istream &in, IntArr& a) { for (int i = 0; i < a.rows; i++) { for (int j = 0; j < a.cols; j++) { in >> a.pa[i][j]; } } return in; } 

you return IntArr as IntArr

 friend istream& operator>>...