Reputation: 44274
If I want my own 1D array class I can overwrite operator[] to read/write the elements. Like:
class A1D {
private:
int a[10]; // This is irrelevant - it's just to simplify the example
// The real class doesn't use a int array.
// Here I just use an int array for simplicity
public:
int& operator[] (int x) { // <--- The interesting part...
return a[x];
}
};
int main()
{
A1D a1d;
a1d[5] = 42;
std::cout << a1d[5] << std::endl;
return 0;
}
The above works fine.
But what if I want to do the same for a 2D array class.
class A2D {
private:
int a[10][10]; // This is irrelevant - it's just to simplify the example
public:
int& operator[][] (int x, int y) { // This, of cause, doesn't work
return a[x][y];
}
};
How would I code [][]
to access elements in the 2D array class?
EDIT - some clarification as the first answers didn't fully do what I needed
I used int
in the example above for simplicity. In the final class I won't use int
so I can't return a int*
and the rely on (*int)[..]
for the second level.
So I'm looking for:
A2D a;
a[3][4] = SomeOtherClass; // Should call function in A2D with arg 3 and 4
SomeOtherClass x = a[3][4]; // Should call function in A2D with arg 3 and 4
Upvotes: 2
Views: 166
Reputation: 4435
You can make a proxy class which will contain a pointer to the corresponding row of the matrix. Unlike the "return the pointer" approach explained in the other answer, this one can be as well applied to 3D and multidimensional matrices.
class RowProxy {
private:
int* row;
public:
explicit RowProxy(int* row) : row(row) {}
int& operator[](int y) {
return row[y];
}
};
class A2D {
private:
int a[10][10]; // This is irrelevant - it's just to simplify the example
public:
RowProxy operator[](int x) {
return RowProxy{a[x]};
}
};
Upvotes: 4
Reputation: 7368
You can return a pointer to an array, for example:
class A2D {
private:
int a[10][10];
public:
int* operator[] (int x) {
return a[x];
}
};
I don't like this solution... I think it's best to have a Row
and a Col
class and return an object, not a raw pointer.
You can also use operator()()
instead of the bracket as an alternative
class A2D {
private:
int a[10][10];
public:
int& operator()(int x, int y) {
return a[x][y];
}
};
A2D arr;
// ...
arr(3, 3) = 5;
Upvotes: 2