Add a range check to for overloaded [] operator : overload bracket operator « Operator Overloading « C++ Tutorial






// A safe array example.
#include <iostream>
#include <cstdlib>
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);
};
   
// Provide range checking for MyClass.
int &MyClass::operator[](int i)
{
  if(i<0 || i> 2) {
    cout << "Boundary Error\n";
    exit(1);
  }
  return a[i];
}
   
int main()
{
  MyClass ob(1, 2, 3);
   
  cout << ob[1]; // displays 2
  cout << " ";
   
  ob[1] = 25;    // [] appears on left
  cout << ob[1]; // displays 25
   
  ob[3] = 44;    // generates runtime error, 3 out-of-range
   
  return 0;
}








10.9.overload bracket operator
10.9.1.Overload ( ) for Point
10.9.2.overloading ( ) for the loc class
10.9.3.The overloaded operator[ ]( ) function returns the value of the array as indexed by the value of its parameter.
10.9.4.design the operator[ ]( ) function in such a way that the [ ] can be used on both the left and right sides of an assignment statement.
10.9.5.Add a range check to for overloaded [] operator
10.9.6.Overload () operator for two values