Overload [] to create a generic safe array type. : Parenthesis « Overload « C++






Overload [] to create a generic safe array type.

  
#include <iostream>
#include <cstdlib>

using namespace std;
template <class T, int len> class safe_array {
  T ar[len];
  int length;

public:
  safe_array();
  T &operator[](int i);

  int getlen() { return length; }
};

template <class T, int len> safe_array<T, len>::safe_array() {
  for(int i=0; i < len; ++i) ar[i] = T();
  length = len;
}

template <class T, int len> T &safe_array<T, len>::operator[](int i)
{
  if(i < 0 || i > len-1) {
    cout << "\nIndex value of " << i << " is out-of-bounds.\n";
    exit(1);
  }
  return ar[i];
}

class myclass {
public:
  int x;
  myclass(int i) { x = i; };
  myclass() { x = -1; }
};

int main()
{
  safe_array<int, 10> intArray;
  safe_array<double, 5> doubleArray;
  int i;

  for(i=0; i < intArray.getlen(); ++i) 
     cout << intArray[i] << endl;

  for(i=0; i < intArray.getlen(); ++i) 
     intArray[i] = i;

  for(i=0; i < intArray.getlen(); ++i) 
     cout << intArray[i] << endl;

  for(i=0; i < doubleArray.getlen(); ++i) 
     cout << doubleArray[i] << endl;

  for(i=0; i < doubleArray.getlen(); ++i) 
     doubleArray[i] = (double) i/3;

  for(i=0; i < doubleArray.getlen(); ++i) 
     cout << doubleArray[i] << endl;

  safe_array<myclass, 3> classArray; // myclass array of size 3

  cout << "Initial values in classArray: ";
  for(i = 0; i < classArray.getlen(); ++i) cout << classArray[i].x << " ";
  cout << endl;

  classArray[0].x = 9;
  classArray[1].x = 9;
  classArray[2].x = -9;

  cout << "New values for classArray: ";
  for(i = 0; i < classArray.getlen(); ++i) cout << classArray[i].x << " ";
  cout << endl;

  intArray[12] = 100;

  return 0;
}
  
    
  








Related examples in the same category

1.Demo: Overload ().Demo: Overload ().
2.Demonstrate the function call operator.
3.Using the Subscript Operator in Programming a Dynamic Array