下標操作符 [] 通常用于訪問數(shù)組元素。重載該運算符用于增強操作 C++ 數(shù)組的功能。
下面的示例演示了如何重載下標運算符 []。
#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 << "索引超過最大值" <<endl;
// 返回第一個元素
return arr[0];
}
return arr[i];
}
};
int main()
{
safearay A;
cout << "A[2] 的值為 : " << A[2] <<endl;
cout << "A[5] 的值為 : " << A[5]<<endl;
cout << "A[12] 的值為 : " << A[12]<<endl;
return 0;
}當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
A[2] 的值為 : 2 A[5] 的值為 : 5 A[12] 的值為 : 索引超過最大值 0