[]必須以類的成員函數的形式進行重載。該函數在類中的聲明格式如下:
返回值類型 & operator[] (參數)
或者:const 返回值類型 & operator[] (參數)
使用第一種聲明方式,運算符重載函數不僅可以訪問對象,同時還可以修改對象。使用第二種聲明方式,運算符重載函數只能訪問而不能修改對象。
#include <iostream>
#include <string>
using namespace std;
class Array{
public:
Array();
Array(int n);
public:
int & operator[](int);
const int & operator[]( int ) const;
int getlength() const{ return m_length; }
private:
int m_length; //數組長度
int *m_pNums; //指向數組內存的指針
};
Array::Array(): m_length(0), m_pNums(NULL){ }
Array::Array(int n): m_length(n){
m_pNums = new int[n];
}
int& Array::operator[](int i){
if(i < 0 || i >= m_length){
throw string("out of bounds");
}
return m_pNums[i];
}
const int & Array::operator[](int i) const{
if(i < 0 || i >= m_length){
throw string("out of bounds");
}
return m_pNums[i];
}
int main(){
Array A(5);
int i;
try{
for(i = 0; i < A.getlength(); i++){
A[i] = i;
}
for(i = 0 ;i < 6; i++ ){
cout<< A[i] <<endl;
}
}catch(string s){
cerr<< s <<", i = "<< i <<endl;
}
return 0;
}
運行結果:本例用到了C++的錯誤處理機制以及 string 類,後續將會講解。本例提供了兩個版本的下標運算符重載函數:
int & operator[]( int );
const int & operator[]( int )const;
arr[5]會被轉換為:
arr.operator[]( 5 );
最後需要說明的是:即使沒有定義 const 版本的重載函數,這段代碼也是可以正確運行的,但是非 const 成員函數不能處理 const 對象,所以在編程時通常會提供兩個版本的運算符重載函數。