下标运算符“[]"重载
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class IntArray
{
private:
int *a;
int sz;
public:
IntArray(int size)
{
sz=size;
a=new int[size];
}
int &operator[](int i)
{
if(i<0||i>=sz)
{
cout<<"ERROR"<<endl;
exit(1);
}
return a[i];
}
~IntArray(){delete[]a;}
};
int main()
{
IntArray a(5);
a[3]=0;
cout<<a[3]<<endl;
a.operator[](3)=3;
cout<<a[3]<<endl;
a.operator[](4)=6;
cout<<a[4]<<endl;
return 0;
}