C++ 中的下標 [] 運算子過載



下標運算子 [] 通常用於訪問陣列元素。此運算子可以被過載以增強 C++ 陣列的現有功能。

以下示例說明了如何過載下標運算子 []。

#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 out of bounds" <<endl; 
            // return first element.
            return arr[0];
         }
         
         return arr[i];
      }
};

int main() {
   safearay A;

   cout << "Value of A[2] : " << A[2] <<endl;
   cout << "Value of A[5] : " << A[5]<<endl;
   cout << "Value of A[12] : " << A[12]<<endl;

   return 0;
}

當以上程式碼編譯並執行時,會產生以下結果:

Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0
cpp_overloading.htm
廣告