Define operator [] : Index « Overload « C++






Define operator []

Define operator []
 
#include <iostream>
using namespace std;

class MyClass {
  int a[3];

public:
  MyClass(int i, int j, int k) {

    a[0] = i;

    a[1] = j;

    a[2] = k;
  }
  int operator[](int i) { 

     return a[i]; 

  }
};

int main()
{
  MyClass object(1, 2, 3);

  cout << object[1];

  return 0;
}


           
         
  








Related examples in the same category

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