C++ 数组 5-- 重载数组下标操作符

#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
    14-41重载数组下标操作符
1)由于函数的参数是数组的下标,因此该函数只能带一个参数。
2)由于下标运算符只限于本类的对象使用,因此不得将下标运算符重载为友元函数
   且必须是非static类的成员函数。
---------------------------------*/
class A
{
public:
A(int l)
{length=l;size=new char[length];}
~A()
{delete []size;}
int getlength()
{return length;}
char &operator[](int i)  //重载下标运算符
{
if(i>=0 && i<length)
return size[i];
else
{
cout<<"\n超出范围";
return size[length-1];
}
}
private:
int length;
char *size;
};
int main()
{
A a(6);               //申请数组空间大小为6
char *ch="hello2B";
for(int i=0;i<8;i++)  //很奇怪,第六个元素不是被赋值为字符'2',而是
{                     //字符串结束标志'\0'
a[i]=ch[i];
}
for(i=0;i<8;i++)
{
cout<<a[i];       //输出打印为"hello"
}
return 0;

}


运行结果:

超出范围

超出范围hello

超出范围

超出范围


猜你喜欢

转载自blog.csdn.net/paulliam/article/details/80030969