作者在 2011-10-29 19:29:02 发布以下内容
h
e
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;
}
e
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;
}
h i=0
e i=1
l i=2
l i=3
o i=4
1 i=5
i=6 size[length-1] 即 size[5] = ch[6] 即'2' 覆盖掉了原来的值'1'
超出范围://此处调用的为a[i] = ch[i]
超出范围://此处调用的为cout << a[i]
2
i=7 size[length-1] 即 size[5] = ch[7] 即为 0 覆盖掉了原来的值'2'
超出范围://此处调用的为a[i] = ch[i]
超出范围://此处调用的为cout << a[i]
h e l l o //0是不可见字符
超出范围://此处调用的为cout << a[6]
超出范围://此处调用的为cout << a[7]
e i=1
l i=2
l i=3
o i=4
1 i=5
i=6 size[length-1] 即 size[5] = ch[6] 即'2' 覆盖掉了原来的值'1'
超出范围://此处调用的为a[i] = ch[i]
超出范围://此处调用的为cout << a[i]
2
i=7 size[length-1] 即 size[5] = ch[7] 即为 0 覆盖掉了原来的值'2'
超出范围://此处调用的为a[i] = ch[i]
超出范围://此处调用的为cout << a[i]
h e l l o //0是不可见字符
超出范围://此处调用的为cout << a[6]
超出范围://此处调用的为cout << a[7]