home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 5-10.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  2KB  |  85 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. class String {
  7.     // . . . .
  8. public:
  9.     char operator[](int);
  10.     int length();
  11.     String operator()(int,int);
  12.     String();
  13.     String(const char *const);
  14.     String operator+(const String&);
  15. };
  16.  
  17. class Atom {
  18. };
  19.  
  20. class NumericAtom: public Atom {
  21. public:
  22.     NumericAtom(): sum(0) { }
  23.     NumericAtom(String &s) {
  24.         sum = 0;
  25.         for (int i = 0; s[i] >= '0' && s[i] <= '9'; i++) {
  26.             sum = (sum*10) + s[i] - '0';
  27.         }
  28.         s = s(i, s.length()-i);
  29.     }
  30.     NumericAtom(const NumericAtom &n) { sum = n.value(); }
  31.     ~NumericAtom() { }
  32.     long value() const { return sum; }
  33.     Atom *copy() {
  34.         NumericAtom *retval = new NumericAtom;
  35.         retval->sum = sum;
  36.         return retval;
  37.     }
  38. private:
  39.     long sum;
  40. };
  41.  
  42. class Name : public Atom {
  43. public:
  44.     Name(): n("") { }
  45.     Name(String& s) { 
  46.         for (int i=0; s[i] >= 'a' && s[i] <= 'z'; i++) {
  47.             n = n + s(i,1);
  48.         }
  49.         s = s(i, s.length()-i);
  50.     }
  51.     Name(const Name& m) { n = m.name(); }
  52.     ~Name() {}
  53.     String name() const { return n; }
  54.     Atom *copy() { Name *retval = new Name;
  55.                    retval->n = n; return retval; }
  56. private:
  57.     String n;
  58. };
  59.  
  60. class Punct : public Atom {
  61. public:
  62.     Punct(): c('\e0')      { }
  63.     Punct(String& s)      { c = s[0]; s = s(1,s.length()-1); }
  64.     Punct(const Punct& p) { c = char(p); }
  65.     operator char() const { return c; }
  66.     ~Punct() {}
  67.     Atom *copy() { Punct *retval = new Punct;
  68.                    retval->c = c;  return retval; }
  69. private:
  70.     char c;
  71. };
  72.  
  73. class Oper : public Atom {
  74. public:
  75.     Oper(): c('\e0') { }
  76.     Oper(String& s) { c = s[0]; s = s(1,s.length()-1); }
  77.     Oper(Oper& o)   { c = char(o); }
  78.     ~Oper() {}
  79.     operator char() const { return c; }
  80.     Atom *copy() { Oper *retval = new Oper;
  81.                    retval->c = c; return retval; }
  82. private:
  83.     char c;
  84. };
  85.