添え字の多重定義

C++パラメーターを 1 つだけ持っている非静的メンバー関数を使用して、 operator[] を多重定義します。 次の例は、多重定義された添え字演算子を持っている単純配列クラスです。 多重定義された添え字演算子は、ユーザーが指定された境界の外で配列にアクセスしようとすると、 例外を throw します。

#include <iostream>
using namespace std;
 
template <class T> class MyArray {
private:
  T* storage;
  int size;
public:
  MyArray(int arg = 10) {
    storage = new T[arg];
    size = arg;
  }
 
  ~MyArray() {
    delete[] storage;
    storage = 0;
  }
 
  T& operator[](const int location) throw (const char *);
};
 
template <class T> T& MyArray<T>::operator[](const int location)
  throw (const char *) {
    if (location < 0 || location >= size) throw "Invalid array access";
    else return storage[location];
}
 
int main() {
  try {
     MyArray<int> x(13);
     x[0] = 45;
     x[1] = 2435;
     cout << x[0] << endl;
     cout << x[1] << endl;
     x[13] = 84;
  }
  catch (const char* e) {
    cout << e << endl;
  }
}

次に、上記の例の出力を示します。

45
2435
Invalid array access

x[1] は、x.operator[](1) と解釈されます。 そして int& MyArray<int>::operator[](const int) を呼び出します。

関連参照

IBM Copyright 2003