添字演算子Subscripting

添字演算子 ([]) は、関数呼び出し演算子のように、二項演算子と見なされます。The subscript operator ([ ]), like the function-call operator, is considered a binary operator. 添字演算子は 1 つの引数を受け取る非静的メンバー関数である必要があります。The subscript operator must be a nonstatic member function that takes a single argument. この引数は任意の型にでき、目的の配列の添字を指定します。This argument can be of any type and designates the desired array subscript.

Example

次の例は、 int 境界チェックを実装する型のベクターを作成する方法を示しています。The following example demonstrates how to create a vector of type int that implements bounds checking:

// subscripting.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class IntVector {
public:
   IntVector( int cElements );
   ~IntVector() { delete [] _iElements; }
   int& operator[](int nSubscript);
private:
   int *_iElements;
   int _iUpperBound;
};

// Construct an IntVector.
IntVector::IntVector( int cElements ) {
   _iElements = new int[cElements];
   _iUpperBound = cElements;
}

// Subscript operator for IntVector.
int& IntVector::operator[](int nSubscript) {
   static int iErr = -1;

   if( nSubscript >= 0 && nSubscript < _iUpperBound )
      return _iElements[nSubscript];
   else {
      clog << "Array bounds violation." << endl;
      return iErr;
   }
}

// Test the IntVector class.
int main() {
   IntVector v( 10 );
   int i;

   for( i = 0; i <= 10; ++i )
      v[i] = i;

   v[3] = v[9];

   for ( i = 0; i <= 10; ++i )
      cout << "Element: [" << i << "] = " << v[i] << endl;
}
Array bounds violation.
Element: [0] = 0
Element: [1] = 1
Element: [2] = 2
Element: [3] = 9
Element: [4] = 4
Element: [5] = 5
Element: [6] = 6
Element: [7] = 7
Element: [8] = 8
Element: [9] = 9
Array bounds violation.
Element: [10] = 10

説明Comments

i前のプログラムでが10に達すると、 operator [] は、範囲外の添字が使用されていることを検出し、エラーメッセージを発行します。When i reaches 10 in the preceding program, operator[] detects that an out-of-bounds subscript is being used and issues an error message.

関数演算子 [] は参照型を返すことに注意してください。Note that the function operator[] returns a reference type. これにより、これが左辺値になり、代入演算子の両側で添字式を使用できるようになります。This causes it to be an l-value, allowing you to use subscripted expressions on either side of assignment operators.

関連項目See also

演算子のオーバーロードOperator Overloading