This question already has an answer here:
- How to overload array index operator for wrapper class of 2D array? 2 answers
I've got a template of a class that shall behave like matrix. So the usecase is something like:
Matrix matrix(10,10);
matrix[0][0]=4;
//set the values for the rest of the matrix
cout<<matrix[1][2]<<endl;
When I set the values directly in the constructor, it works well, but when I want to use matrix[x][y]=z;
I get error: lvalue required as left operand of assignment
. I assume, that I must overload =
operator. Nevertheless I tried whole evening and I didn't find out, how to implement it. Would anybody be please so kind and show me how to overload =
operator for my code, to make it assign values to that matrix?
code:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sstream>
using namespace std;
class Matrix {
public:
Matrix(int x,int y) {
_arrayofarrays = new int*[x];
for (int i = 0; i < x; ++i)
_arrayofarrays[i] = new int[y];
// works here
_arrayofarrays[3][4] = 5;
}
class Proxy {
public:
Proxy(int* _array) : _array(_array) {
}
int operator[](int index) {
return _array[index];
}
private:
int* _array;
};
Proxy operator[](int index) {
return Proxy(_arrayofarrays[index]);
}
private:
int** _arrayofarrays;
};
int main() {
Matrix matrix(5,5);
// doesn't work :-S
// matrix[2][1]=0;
cout << matrix[3][4] << endl;
}