Program to Overload [ ] Subscript Operator:
#include<iostream>
using namespace std;
class sample
{
int a[10]; //private data
public: int n;
sample()
{
cout<<"Enter The No of Elements of Array ";
cin>>n;
cout<<"Enter The Elements\n";
for(int i=0;i<n;i++)
cin>>a[i];
}
int operator [](int k) // overloading Subscript operator
{
return(a[k]);
}
};
main()
{
sample a;
cout<<"Elements You Entered\n";
for(int i=0;i<a.n;i++)
cout<<a[i]<<"\n"; //fetching private data using object
}
Output:
#include<iostream>
using namespace std;
class sample
{
int a[10]; //private data
public: int n;
sample()
{
cout<<"Enter The No of Elements of Array ";
cin>>n;
cout<<"Enter The Elements\n";
for(int i=0;i<n;i++)
cin>>a[i];
}
int operator [](int k) // overloading Subscript operator
{
return(a[k]);
}
};
main()
{
sample a;
cout<<"Elements You Entered\n";
for(int i=0;i<a.n;i++)
cout<<a[i]<<"\n"; //fetching private data using object
}
Output: