After the code get compile my , while the program trying to access the private array it got stucked. i build a constructor and in this function i can print the array but after that if im trying to access the array from another function its not working.
In this code it stuck while working on mat(1,2) - trying to return arr[1][2]:
i tried to allocate the array in a different way, to make [] operator but nothing seems to work.
main file :
#include "matrix.h"
#include <iostream>
int main() {
Matrix<4, 4> mat;
mat(1,2);
std::cout << mat << std::endl;
return 0;
}
.h file :
#ifndef matrix_h
#define matrix_h
#include <iostream>
template <int row, int col ,typename T=int>
class Matrix {
public:
Matrix(int v = 0) { // constructor with deafault value of '0'
int **arr = new int*[row]; //initializing place for rows
for (int j = 0;j < row;j++) {
arr[j] = new int[col];
}
for (int i = 0;i < row;i++)
for (int j = 0;j < col;j++)
arr[i][j] = v;
}
T& operator () (int r, int c) const {
return arr[r][c];
}
friend std::ostream& operator<<(std::ostream& out,const Matrix <row,col,T> mat) {
for (int i = 0;i < row;i++) {
for (int j = 0;j < col;j++) {
out << mat(i,j) << " ";
}
out << std::endl;
}
return out;
}
private:
T** arr;
};
#endif //matrix_h