home *** CD-ROM | disk | FTP | other *** search
/ Turbo Toolbox / Turbo_Toolbox.iso / dtx9203 / borhot / obrack.cpp < prev    next >
C/C++ Source or Header  |  1992-03-24  |  2KB  |  60 lines

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