我們常用下標運算符operator[]來訪問數組中的某個元素.它是一個雙目運算符,第一個運算符是數組名,第二個運算符是數組下標.在類對象中,我們可以重載下標運算符,用它來定義相應對象的下標運算.
注意,C++不允許把下標運算符函數作爲外部函數來定義,它只能是非靜態的成員函數.下標運算符定義的一般形式:
T1T::operator[](T2);
其中,T是定義下標運算符的類,它不必是常量.T2表示下標,它可以是任意類型,如整形,字符型或某個類.T1是數組運算的結果.它也可以是任意類型,但爲了能對數組賦值,一般將其聲明爲引用形式.在有了上面的定義之後,可以採用下面兩種形式之任一來調用它:
x[y]
或x.operator[](y)
x的類型爲T,y的類型爲T2.
下面來看一個簡單的例子:
#include<iostream.h>
class aInteger
{
public:
aInteger(int size)
{
sz = size;
a = new int[size];
}
int& operator [] (int i);
~aInteger()
{
delete []a;
}
private:
int*a;
intsz;
};
int& aInteger::operator [](inti)
{
if(i < 0 || i > sz)
{
cout << "error, leap the pale"<< endl;
}
return a[i];
}
int main()
{
aInteger arr(10);
for(int i = 0; i < 10; i++)
{
arr[i] = i+1;
cout << arr[i]<< endl;
}
intn = arr.operator [] (2);
cout<< "n = "<< n <<endl;
return 0;
}
在整形數組ainteger中定義了下標運算符,這種下標運算符能檢查越界的錯誤。現在使用它:
ainteger ai(10);
ai[2]=3;
int i=ai[2];
對於ai[2]=3,他調用ai.operator(2),返回對ai::a[2]的引用,接着再調用缺省的賦值運算符,把3的值賦給此引用,因而ai::a[2]的值爲3。注意,假如返回值不採用引用形式,ai.operator(2)的返回值是一臨時變量,不能作爲左值,因而,上述賦值會出錯。對於初始化i=ai[2],先調用ai.operator(2)取出ai::a[2]的值。然後再利用缺省的複製構造函數來初始化i.
實例:
//**********************************
//*** 下標重載運算符 ***
//**********************************
#include<iostream.h>
class charArray
{
public:
charArray(int len)
{
length = len;
buffer = new char[length];
}
intgetLength()
{
return length;
}
char& operator[](int i);
~charArray()
{
delete[]buffer;
}
private:
intlength;
char* buffer;
};
char& charArray::operator[] (inti)
{
static char ch = 0;
if(i >= 0 && i< length)
return buffer[i];
else
{
cout << "out of range!"<< endl;
return ch;
}
}
int main()
{
inti;
charArray str1(7);
char* str2 = "string";
for(i = 0; i < 7; i++)
{
str1[i] = str2[i];
}
for(i = 0; i < 7; i++)
{
cout << str1[i];
}
cout<< str1.getLength()<< endl;
return 0;
}