My goal was to implement my own Matrix class in C++. Firstly, I wanted to access an element using two consecutive subscript operator[]
. However, when I tried to overload it, I came across an error of invalid initialization of non-const reference of type 'Matrix::Line&' from an rvalue of type 'Matriz::Line
.
I've found out that only if I made it static then it'd work, but I can't explain what's going on with that static
qualifier. Why did it work just that way but with wrong output?
class Matrix{
int ** matrix;
int lines, cols;
public:
class Line{
int *line;
public:
Line(int* l):line(l){};
Line(){};
int& operator[](size_t i){
return line[i];
}
};
Matrix(int lin, int col):lines(lin), cols(col){
matrix = new int*[lines];
for(int i = 0; i < lines; i++){
matrix[i] = new int[cols];
for(int j = 0; j < cols; j++) matrix[i][j] = 0; // initialize 0s
}
}
~Matrix(){
for(int i = 0; i < lines; i++) delete[] matrix[i];
delete[] matrix;
}
Line& operator[](size_t i){
return Line(matrix[i]); // error!
// static Line legit(matrix[i]); --> works
// return legit;
}
};
Plus, when I do:
int x = 4, y = 4;
Matrix M(x,y);
M[0][0] = 3;
for(int i = 0; i < x; i++){
for(int j = 0; j < y; j++) cout << M[i][j] << " ";
cout << "\n";
}
Output:
3 0 0 0 0
3 0 0 0 0
3 0 0 0 0
3 0 0 0 0
I can't see why it changes every row!