English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C++ Operator Overloading and Overloaded Functions
The subscript operator [] is usually used to access array elements. Overloading this operator is used to enhance operations in C++ Array functionality.
The following example demonstrates how to overload the subscript operator [].
#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 << "A[2] The value is : " << A[2] << endl; cout << "A[5] The value is : " << A[5] << endl; cout << "A[12] The value is : " << A[12] << endl; return 0; }
When the above code is compiled and executed, it will produce the following results:
A[2] The value is : 2 A[5] The value is : 5 A[12The value of ] is : Index exceeds maximum value 0