/* C++ program to overload [] operator */
#include<iostream>
#include<stdlib.h>
using namespace std;
class overload
{
private:int *p;
int s;
public: overload(int *,int);
int & operator[](int);
void showdata()const;
~overload();
};
overload :: overload(int *ptr=NULL,int s1=0)
{
p=NULL;
s=s1;
if(s!=0)
{
p=new int[s];
for(int i=0;i<s;i++)
p[i]=ptr[i];
}
cout<<"\n Object created....";
}
int & overload :: operator[](int x)
{
if(x>=s)
{
cout<<"\n Array is out of bounded";
exit(0);
}
return(p[x]);
}
void overload :: showdata()const
{
cout<<"\n The element of array:";
for(int i=0;i<s;i++)
cout<<"\n\t\t\t" <<p[i];
}
overload :: ~overload()
{
delete[] p;
}
int main()
{
int a[ ]={1,2,3,4,5};
overload q(a,5);
overload w;
q.showdata();
q[2]=6;
q.showdata();
q[8]=10;
q.showdata();
w.showdata();
return(0);
}
No comments:
Post a Comment