home *** CD-ROM | disk | FTP | other *** search
/ Using Visual C++ 4 (Special Edition) / Using_Visual_C_4_Special_Edition_QUE_1996.iso / ch14 / train2.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1995-09-18  |  1.9 KB  |  99 lines

  1. #include <iostream.h>
  2. #include <afx.h>
  3.  
  4. // Things to put in a RailroadCar
  5. class Cow {
  6. public:
  7.     // Public member functions
  8.     CString isA() { return "Cow"; }
  9.     CString Moo() { return "Moo!"; }
  10. };
  11.  
  12. class Passenger {
  13. public:
  14.     // Constructors and destructor
  15.     Passenger(CString NewName) { Name = NewName; }
  16.  
  17.     // Public member functions
  18.     CString isA() { return "Passenger"; }
  19.     CString GetName() { return Name; }
  20.     CString Complain() { return "Oh my poor back!"; }
  21.  
  22. private:
  23.     CString Name;
  24. };
  25.  
  26.  
  27. // The RailroadCar class template
  28. template <class T>
  29. class RailroadCar {
  30. public:
  31.     // Constructors and destructor
  32.     RailroadCar(int NewCarNumber, T& NewContents);
  33.     ~RailroadCar();
  34.  
  35.     // Public member functions
  36.     void ShowContents();
  37.     T* Unload();
  38.  
  39. private:
  40.     T* pContents;
  41.     int CarNumber;
  42. };
  43.  
  44. // Constructor
  45. template <class T>
  46. RailroadCar<T>::RailroadCar(int NewCarNumber,
  47.                             T&  NewContents)
  48. {
  49.     CarNumber = NewCarNumber;
  50.     pContents = &NewContents;
  51. }
  52.  
  53. // Destructor
  54. template <class T>
  55. RailroadCar<T>::~RailroadCar()
  56. {
  57.     Unload();
  58. }
  59.  
  60. // Public member functions
  61. template <class T>
  62. void RailroadCar<T>::ShowContents()
  63. {
  64.     cout << "Railroad car #" << CarNumber;
  65.     cout << " is filled with " << pContents->isA();
  66.     cout << "s\n";
  67. }
  68.  
  69. template <class T>
  70. T* RailroadCar<T>::Unload()
  71. {
  72.     T* temp = pContents;
  73.     pContents = NULL;
  74.     return temp;
  75. }
  76.  
  77. // ShowContents specialization for integers
  78. void RailroadCar<int>::ShowContents()
  79. {
  80.     cout << "Railroad car #" << CarNumber;
  81.     cout << " is filled with an integer (" << *pContents;
  82.     cout << ")\n";
  83. }
  84.  
  85. void main()
  86. {
  87.     int IntegerCargo = 456;
  88.     Cow Bessie;
  89.     RailroadCar<int> CarNumber1(1, IntegerCargo);
  90.     RailroadCar<Cow> CarNumber2(2, Bessie);
  91.  
  92.     // Calls the int specialization
  93.     CarNumber1.ShowContents();
  94.  
  95.     // Calls the normal template member function that
  96.     // relies on isA
  97.     CarNumber2.ShowContents();
  98. }
  99.