C ++ - run on object, overload operator () with index
I have a class to represent a two dimensional array and I want to use the () operator, for example
Array arr;
arr(2,5) = 17; // I want to assign 17 as element in 2nd row and 5th column.
I've tried something like this: (but doesn't work)
void operator(int m, int n)(int num) {
int m, n;
p[m][n] = num;
}
i has operator = (this work):
void operator=(const Array& other) const {
for (int i = 0; i < DIM; i++) {
for (int j = 0; j < DIM; j++) {
p[i][j] = other.p[i][j];
}
}
}
Array
the class has T**
as a private member.
How can I overload operator ()
to access elements in an array
Thank!
source to share
You need to build something like
int& operator()(int m, int n)
which returns a link to an array element, which you can modify via that link on the calling site.
Don't forget to create an overload const
const int& operator()(int m, int n) const
so that you can use a similar syntax in the calling site to access the element for the object const
.
Finally, for your assignment operator, you shouldn't be doing it const
(did you p mutable
?), And you should return a reference to self to help the compound assignment:
Array& operator=(const Array& other){
// Your existing code
return *this;
}
Link: http://en.cppreference.com/w/cpp/language/copy_assignment
source to share