C++ Subscript Operator [] Overloading

C++ Operator Overloading and Function Overloading

The subscript operator [] is typically used to access array elements. Overloading this operator serves to enhance the functionality of manipulating C++ arrays.

The following example demonstrates how to overload the subscript operator [].

Example

#include <iostream> using namespace std; const int SIZE = 10; class safearay { private: int arr[SIZE]; public: safearay() { register int i; for(i = 0; i < SIZE; i++) { arr[i] = i; } } int& operator[](int i) { if( i >= SIZE ) { cout << "Index exceeds maximum value" <<endl; // Return the first element return arr[0]; } return arr[i]; } }; int main() { safearay A; cout << "The value of A[2] is:" << A[2] <<endl; cout << "The value of A[5] is:" << A[5]<<endl; cout << "The value of A[12] is:" << A[12]<<endl; return 0; }

When the above code is compiled and executed, it produces the following results:

$ g++ -o test test.cpp
$ ./test 
A[2] 的值为 : 2
A[5] 的值为 : 5
A[12] 的值为 : 索引超过最大值
0

C++ Operator Overloading and Function Overloading

other extensions