home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / library / dos / diverses / tctnt / obrack.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-28  |  1.2 KB  |  51 lines

  1. /* OBRACK.CPP: Overloading Bracket Operator for Array Range Checking
  2. */
  3.  
  4. #include <stdio.h>            // for fprintf() and stderr
  5. #include <stdlib.h>            // for exit()
  6. #include <conio.h>            // for clrscr()
  7.  
  8. #define size 10
  9.  
  10. class array{
  11.         int index;
  12.         unsigned linear[size];
  13.         void error(char * msg);
  14.     public:
  15.         array(unsigned value = 0);
  16.         unsigned & operator[](int index);
  17. };
  18.  
  19. void array::error(char *msg) {
  20.     fprintf(stderr, "Array Error: %s\n", msg);
  21. }
  22.  
  23. array::array(unsigned value) {
  24.     for (int i = 0; i < size; i++)
  25.         linear[i] = value;
  26. }
  27.  
  28. unsigned & array::operator[](int index) {
  29.     char msg[30];
  30.     if (index < 0 ) {
  31.         sprintf(msg, "array index must be >= 0.");
  32.         error(msg);
  33.     }
  34.     if (index >= size) {
  35.         sprintf(msg, "array index must be < %d.", size);
  36.         error(msg);
  37.     }
  38.     return linear[index];
  39. }
  40.  
  41. //*******************************************************************
  42. int main()
  43. {
  44.     clrscr();
  45.     array a(0);                // create array of 10 elements and init to 0
  46.     a[0] = 5;                    // ok because 0 >= 5 < 10
  47.     a[100] = 10;            // Array Error: "array index must be < 10."
  48.     a[-1] = 15;                // Array Error: "array index must be >= 0."
  49.     return 0;
  50. } // end of main()
  51.