I've been reading up on class operators and came across the following example:
class Array {
public:
int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];
};
Does this mean I can replace [
and ]
with whatever I want? For example, could I use parentheses?
Also, what is the significance of the ampersand in int& operator[]
?
On a slightly less important note, would it be syntactically correct to use int& operator []
instead of int& operator[]
?
Does this mean I can replace [ and ] with whatever I want?
Nopes! Not all operators can be overloaded.
For example, could I use parentheses?
You can but you shouldn't.
Also, what is the significance of the ampersand in
int& operator[]
?
It means you are returning a reference to an int
variable.
EDIT: On a slightly less important note, would it be syntactically correct to use
int& operator []
instead ofint& operator[]
?
There is no difference between the two.
What you are doing is defining an Array class that wrapes a simple integer array. By overloading the [] operator you can acces each element of the array as with any other array, the advantage here is that your are checking superior limit to avoid buffer overflow. The ampersand means that you are returning a reference to the array element, it allows you both assigment a value and getting a value. In c++ when you overload the [] operator dont forget both const and non-const versions:
int& operator[] (conts int a) {...}
int operator[] (conts int a) {...} const
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With