As mentioned earlier, the subscript operator []
must be overloaded in the form of a member function of the class. The declaration format in the class is as follows:
operator [] (parameter)
Or
Const operator [] (parameter)
Using the first method of declaration, the operator overload function can not only access the object, but also modify the object. With the second way of declaring, an operator overload function can only be accessed without modifying an object.
By default, accessing elements in an array by subscript does not have the check Boundary overflow feature, which we can implement by overloading.
Take a look at the following code:
#include <iostream>#include<string>using namespacestd;classarray{Private: intlength; int*num; Public: Array (): Length (0), num (NULL) {} Array (intN); int&operator[](int); Const int&operator[](int)Const; intGetLength ()Const{returnlength;}}; Array::array (intN) {num=New int[n]; Length=N;}int& Array::operator[](inti) { if(I <0|| I >=length)Throw string("Out of bounds"); returnnum[i];}Const int& Array::operator[](intIConst{ if(I <0|| I >=length)Throw string("Out of bounds"); returnnum[i];}intMain () {Array A (5); inti; Try{ for(i =0; I < a.getlength (); i++) A[i]=i; for(i =0; I <6; i++) cout<< A[i] <<Endl; }Catch(strings) {Cerr<< s <<", i ="<< I <<Endl; } return 0;}
This example provides two versions of the subscript operator overload function:
int operator int ); Const int operator int ) Const;
The first function without the const, plus the const means that the member function is a constant member function, if the first function is also added to the const, then two functions only the return value is different, the compiler can not distinguish this is a function overload, will error. These two versions of the overloaded functions are well understood, the first one can modify the object, the second can only access the object and cannot modify the object.
After overloading the subscript operator [], "arr[5" is converted to:
Arr.operator[] (5);
The last thing to note is that this code can run correctly even if there are no overloaded functions that define the const version, but non-const member functions cannot handle const objects, so you will typically provide two versions of the operator overloading function when programming.
C + + Learning 29 overloading [] (subscript operator)