额....重载数组下标操作符,有点晕,希望高手指点...谢谢
he
l
l
o
1
超出范围:
超出范围:
2
超出范围:
超出范围:
上面啊是结果:
程序:
#include<iostream>
using namespace std;
class A
{
public:
A(int l){length=l;size=new char[length];}
~A(){delete [] size;}
int getlength(){return length;}
char&operator[](int i);
private:
int length;
char*size;
};
char&A::operator[](int i)
{
if(i>=0&&i<length)
return size[i];
else
{
cout<<"\n超出范围:"<<endl;
return size[length-1];
}
}
int main()
{
int i;
A a(6);
char*ch="hello12";
for(i=0;i<8;i++)
{
a[i]=ch[i];
cout<<a[i];
cout<<endl;
}
for(i=0;i<8;i++)
cout<<a[i]<<"\t";
cout<<a.getlength();
system("pause");
return 0;
}
[ 本帖最后由 lianjiecuowu 于 2011-5-29 13:27 编辑 ]