C++ 下标运算符 [] 重载


下标操作符 [] 通常用于访问数组元素。这个运算符符可被重载用于增强操作 C++ 数组的功能。

下面的实例演示了如何重载下标运算符 []。

  1. #include <iostream>
  2. using namespace std;
  3. const int SIZE = 10;
  4.  
  5. class safearay
  6. {
  7. private:
  8. int arr[SIZE];
  9. public:
  10. safearay()
  11. {
  12. register int i;
  13. for(i = 0; i < SIZE; i++)
  14. {
  15. arr[i] = i;
  16. }
  17. }
  18. int &operator[](int i)
  19. {
  20. if( i > SIZE )
  21. {
  22. cout << "Index out of bounds" <<endl;
  23. // 返回第一个元素
  24. return arr[0];
  25. }
  26. return arr[i];
  27. }
  28. };
  29. int main()
  30. {
  31. safearay A;
  32.  
  33. cout << "Value of A[2] : " << A[2] <<endl;
  34. cout << "Value of A[5] : " << A[5]<<endl;
  35. cout << "Value of A[12] : " << A[12]<<endl;
  36.  
  37. return 0;
  38. }

当上面的代码被编译和执行时,它会产生下列结果:

  1. Value of A[2] : 2
  2. Value of A[5] : 5
  3. Index out of bounds
  4. Value of A[12] : 0