Index operator for class : Index « Overload « C++






Index operator for class

  
#include <iostream>
#include <stdlib.h>
using namespace std;
class sometype {
  int a[3];
  public:
   sometype(int i, int j, int k)
    {
      a[0] = i;
      a[1] = j;
      a[2] = k;
    }
   int &operator[](int i);
};

int &sometype::operator[](int i)
{
   if (i<0 || i>2)
    {
      cout << "Boundary error.\n";
      exit(1);
    }
   return a[i];
}


int main(void)
{
   sometype ob(1, 2, 3);

   cout << ob[1];
   cout << endl;
   ob[1] = 25;
   cout << endl;
   cout << ob[1];
   ob[3] = 44;
}
  
    
  








Related examples in the same category

1.Operator overload: new, delete, new[] and delete[]Operator overload: new, delete, new[] and delete[]
2.Define operator []Define operator []
3.Overload [].Overload [].
4.Return a reference from [].Return a reference from [].
5.String class: Index characters and '=' operatorString class: Index characters and '=' operator