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

  1. #include <iostream.h>
  2.  
  3. // Define the Boolean type
  4. typedef unsigned char Boolean;
  5. const Boolean TRUE = 1;
  6. const Boolean FALSE = 0;
  7.  
  8. // GlobalValue template definition
  9. template <class T>
  10. class GlobalValue {
  11. public:
  12.     // Constructors and destructor
  13.     GlobalValue();
  14.     GlobalValue(T* pNewGlobalValue);
  15.     ~GlobalValue();
  16.  
  17.     // Public member functions
  18.     static T* GetGlobalValuePtr();
  19.  
  20. private:
  21.     static T* pGlobalValue;
  22.     static Boolean ShouldDelete;
  23. };
  24.  
  25. // Initialize static data
  26. template <class T>
  27. T* GlobalValue<T>::pGlobalValue = NULL;
  28. template <class T>
  29. Boolean GlobalValue<T>::ShouldDelete = FALSE;
  30.  
  31. // Constructors
  32. template <class T>
  33. GlobalValue<T>::GlobalValue()
  34. {
  35.     pGlobalValue = new T;
  36.     ShouldDelete = TRUE;
  37. }
  38.  
  39. template <class T>
  40. GlobalValue<T>::GlobalValue(T* pNewGlobalValue)
  41. {
  42.     pGlobalValue = pNewGlobalValue;
  43.     ShouldDelete = FALSE;
  44. }
  45.  
  46. // Destructor
  47. template <class T>
  48. GlobalValue<T>::~GlobalValue()
  49. {
  50.     if (ShouldDelete && pGlobalValue)
  51.         delete pGlobalValue;
  52. }
  53.  
  54. // Public member functions
  55. template <class T>
  56. T* GlobalValue<T>::GetGlobalValuePtr()
  57. {
  58.     return pGlobalValue;
  59. }
  60.  
  61.  
  62. // Now demonstrate use of a GlobalValue
  63. void AFarAwayFunc()
  64. {
  65.     cout << "The int GlobalValue is ";
  66.     cout << *GlobalValue<int>::GetGlobalValuePtr() << endl;
  67. }
  68.  
  69. void main()
  70. {
  71.     int AVeryImportantInt = 123;
  72.     GlobalValue<int> GlobalInt(&AVeryImportantInt);
  73.  
  74.     // Show the current value
  75.     AFarAwayFunc();
  76.  
  77.     // Change the value
  78.     AVeryImportantInt++;
  79.     AFarAwayFunc();
  80. }
  81.