Posted on 2012-02-24 00:08
hoshelly 閱讀(1662)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C++
為防止在對(duì)數(shù)組動(dòng)態(tài)賦值時(shí)發(fā)生數(shù)組越界,C++提供了一種能夠解決此問(wèn)題的方法——重載運(yùn)算符[]。示例程序:
#include<iostream>
class CArray
{
public:
CArray(int l)
{
length=l;
Buff=new char[length];
}
~CArray(){delete Buff;}
int GetLength(){return length;}
char& operator [](int i);
private:
int length;
char *Buff;
};
char & CArray::operator[](int i)
{
static char ch=0;
if(i<length && i>=0)
return Buff[i];
else
{
cout<<"\nIndex out of range.";
return ch;
}
}
void main()
{
int cnt;
CArray string1(6);
char *string2="string";
for(cnt=0;cnt<string1.GetLength();cnt++)
string1[cnt]=string2[cnt];
cout<<"\n";
for(cnt=0;cnt<string1.GetLength();cnt++)
cout<<string1[cnt];
cout<<"\n";
cout<<string1.GetLength()<<endl;
}
在重載下標(biāo)運(yùn)算符函數(shù)時(shí)注意:
1)該函數(shù)只帶一個(gè)參數(shù),不可帶多個(gè)參數(shù)。
2)得重載為友元函數(shù),必須是非static類的成員函數(shù)。