[ create a new paste ] login | about

Link: http://codepad.org/sOLpXE35    [ raw code | output | fork ]

C++, pasted on Apr 3:
// Overloading the c++ array subscript operator [ ]

#include<iostream>
using namespace std;

const int size=10;

class myArray
{
      int a[size];
    public:
      myArray()
      {}
      int & operator [](int);
      void print_array();   
};

int& myArray::operator [](int x) // This is the line where error is as by compiler
{
          return a[x];
}

void myArray::print_array()
{
    for (int j=0; j < 10; j++)
        cout<<"array["<<j<<"] = "<<a[j]<<"\n";
}

int main()
{
    myArray instance;
    for (int i=0; i < size; i++)
     {
       instance[i] = i;
     }  
    instance.print_array();

    cout<<"\n\n";
    return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
array[5] = 5
array[6] = 6
array[7] = 7
array[8] = 8
array[9] = 9




Create a new paste based on this one


Comments: