Cplusplus-subscripting-operator-overloading
提供:Dev Guides
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