class matrix {
public:
int **A;
int nrColoane;
int nrLinii;
public:
int& operator[] (int nrLinii, int nrColoane);
};
Asked
Active
Viewed 142 times
0
-
It is common practice to use the function call operator instead since it can take multiple arguments. – chris Nov 22 '14 at 21:01
-
3To do this for 2d matrix and operator [] you need to return what is known as a proxy object. It contains a pointer to the original object and the specified row. Its operator [] will then retrieve the value for the column. But it's simpler to use operator (). Ps using a 1d vector for your data and the index calculation `x + y * width` is more efficient. – Neil Kirk Nov 22 '14 at 21:23
-
1@Neil: Please, comments are second-class citizens and can be deleted at any time so putting this wisdom in a comment is utterly pointless. Write an _answer_! – Lightness Races in Orbit Nov 22 '14 at 22:03
2 Answers
1
I'm afraid this is not possible. The common way to solve your problem is to overload operator ().
class Matrix {
public:
int& operator () (int i, int j);
};

user2008934
- 321
- 2
- 9
1
As others have mentioned, it's common to solve the problem using operator()
. An alternative is to still use operator[]
taking one argument, but return an object that represents a row (and keeps a reference to the original object). Then the row object will again implement operator[]
and return the actual value.

Jiří Pospíšil
- 14,296
- 2
- 41
- 52