E
ek
In the class below I overload the "()" operator. When reading an
element in an int array "()" is therefore used. But why can't I still
use "[]" when writing something like a[2] = 4;
class MyArray {
public:
MyArray(int a) : data(new int[a]){}
~MyArray() {delete[] data;}
int& operator()(int a){
return data[a];
}
int operator()(int a) const{
return data[a];
}
private:
int* data;
};
int main() {
MyArray Arr(4);
Arr[2] = 5; // error: no match for 'operator[]' in 'Arr[2]'
return 0;
}
When overloading "()" the normal "[]" operator no longer works. I can
instead do the assignment with Arr(2) = 5; but I have not specified an
overload of "()" that does assignment, why is that not needed?
element in an int array "()" is therefore used. But why can't I still
use "[]" when writing something like a[2] = 4;
class MyArray {
public:
MyArray(int a) : data(new int[a]){}
~MyArray() {delete[] data;}
int& operator()(int a){
return data[a];
}
int operator()(int a) const{
return data[a];
}
private:
int* data;
};
int main() {
MyArray Arr(4);
Arr[2] = 5; // error: no match for 'operator[]' in 'Arr[2]'
return 0;
}
When overloading "()" the normal "[]" operator no longer works. I can
instead do the assignment with Arr(2) = 5; but I have not specified an
overload of "()" that does assignment, why is that not needed?