home *** CD-ROM | disk | FTP | other *** search
- #include <iostream.h>
- #include <afx.h>
-
- // Things to put in a RailroadCar
- class Cow {
- public:
- // Public member functions
- CString isA() { return "Cow"; }
- CString Moo() { return "Moo!"; }
- };
-
- class Passenger {
- public:
- // Constructors and destructor
- Passenger(CString NewName) { Name = NewName; }
-
- // Public member functions
- CString isA() { return "Passenger"; }
- CString GetName() { return Name; }
- CString Complain() { return "Oh my poor back!"; }
-
- private:
- CString Name;
- };
-
-
- // The RailroadCar class template
- template <class T>
- class RailroadCar {
- public:
- // Constructors and destructor
- RailroadCar(int NewCarNumber, T& NewContents);
- ~RailroadCar();
-
- // Public member functions
- void ShowContents();
- T* Unload();
-
- private:
- T* pContents;
- int CarNumber;
- };
-
- // Constructor
- template <class T>
- RailroadCar<T>::RailroadCar(int NewCarNumber,
- T& NewContents)
- {
- CarNumber = NewCarNumber;
- pContents = &NewContents;
- }
-
- // Destructor
- template <class T>
- RailroadCar<T>::~RailroadCar()
- {
- Unload();
- }
-
- // Public member functions
- template <class T>
- void RailroadCar<T>::ShowContents()
- {
- cout << "Railroad car #" << CarNumber;
- cout << " is filled with " << pContents->isA();
- cout << "s\n";
- }
-
- template <class T>
- T* RailroadCar<T>::Unload()
- {
- T* temp = pContents;
- pContents = NULL;
- return temp;
- }
-
- // ShowContents specialization for integers
- void RailroadCar<int>::ShowContents()
- {
- cout << "Railroad car #" << CarNumber;
- cout << " is filled with an integer (" << *pContents;
- cout << ")\n";
- }
-
- void main()
- {
- int IntegerCargo = 456;
- Cow Bessie;
- RailroadCar<int> CarNumber1(1, IntegerCargo);
- RailroadCar<Cow> CarNumber2(2, Bessie);
-
- // Calls the int specialization
- CarNumber1.ShowContents();
-
- // Calls the normal template member function that
- // relies on isA
- CarNumber2.ShowContents();
- }
-