home *** CD-ROM | disk | FTP | other *** search
/ C++ for Dummies (3rd Edition) / C_FD.iso / CHAP16 / CHAP16_2.CPP < prev   
C/C++ Source or Header  |  1996-09-15  |  2KB  |  76 lines

  1. // Chap16_2.cpp
  2. #include <iostream.h>
  3. #include <string.h>
  4. class Student
  5. {
  6.   public:
  7.    //same constructor and destructor as earlier
  8.    Student(char *pName  = "no name")
  9.    {
  10.       strcpy(name, pName);
  11.       noOfStudents++;    // count us
  12.       pNext = pFirst;    // add us to front of list
  13.       pFirst= this;
  14.    }
  15.   ~Student()
  16.    {
  17.       noOfStudents--;
  18.  
  19.       Student* pS;       // remove us from list
  20.       if (pFirst == this)
  21.       {
  22.           pFirst = pNext;
  23.       }
  24.       else
  25.       {
  26.           // look for the guy in front of us...
  27.           for (pS = pFirst; pS; pS = pS->pNext)
  28.           {
  29.               if (pS->pNext == this)
  30.               {
  31.                   // ...change his next pointer to
  32.                   // "go around" us
  33.                   pS->pNext = pNext;
  34.                   break;
  35.               }
  36.           }
  37.       }
  38.    }
  39.  
  40.    //findName - return student w/specified name
  41.    static Student *findName(char *pName);
  42.   protected:
  43.    static Student *pFirst;
  44.    Student *pNext;
  45.    char name[40];
  46.    static int noOfStudents;
  47. };
  48. Student* Student::pFirst = 0;
  49. int Student::noOfStudents = 0;
  50. //findName - return the Student with the specified name.
  51. //           Return zero if no match.
  52. Student* Student::findName(char *pName)
  53. {
  54.    //loop thru the linked list...
  55.    for (Student *pS = pFirst; pS; pS = pS->pNext)
  56.    {
  57.       //...if we find the specified name...
  58.       if (strcmp(pS->name, pName) == 0)
  59.       {
  60.          //...then return the objectÆs address
  61.          return pS;
  62.       }
  63.    }
  64.    //...otherwise, return a zero (item not found)
  65.    return (Student*)0;
  66. }
  67.  
  68. int main()
  69. {
  70.    Student s1("Randy");
  71.    Student s2("Jenny");
  72.    Student s3("Kinsey");
  73.    Student *pS = Student::findName("Jenny");
  74.    return 0;
  75. }
  76.