home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / tmplt.zip / TMPLT2.CPP < prev   
Text File  |  1994-03-21  |  2KB  |  64 lines

  1. /*----------------------------------------------------------------------------*/
  2. /* tmplt2.cpp                                                                 */
  3. /*                                                                            */
  4. /* template example - class with a template,  conversion constructor, and an  */
  5. /*                    example of initialization with the "=" operator.        */
  6. /*                                                                            */
  7. /* (c) Larry Morley, 1994                                                     */
  8. /*----------------------------------------------------------------------------*/
  9.  
  10. #include <stdio.h>
  11.  
  12. int main(void);
  13.  
  14. /*----------------------------------------------------------------------------*/
  15.  
  16. template<class DataType>
  17. class MathClass
  18. {
  19.    private:
  20.  
  21.       DataType Value;  // The actual value of the object.
  22.  
  23.    public:
  24.  
  25.       MathClass(DataType InitialValue)  // Constructor - allows the "=" in
  26.       {                                 // main() to pass a value instead
  27.          Value = InitialValue;          // of having to use an explicit
  28.       }                                 // classname(value) constructor.
  29.  
  30.       operator DataType() // Allows variable to be used as if it were
  31.       {                   // of the specified data type.
  32.          return Value;
  33.       }
  34.  
  35.       multiply(DataType Num1,DataType Num2)  // Define some member functions.
  36.       {
  37.          return Num1 * Num2;
  38.       }
  39.  
  40.       divide(DataType Num1,DataType Num2)
  41.       {
  42.          return Num1 / Num2;
  43.       }
  44.  
  45.       // etc.
  46. };
  47.  
  48. /*----------------------------------------------------------------------------*/
  49.  
  50. int main()
  51. {
  52.    MathClass<int> x = 5;  // The "=" invokes the constructor.
  53.    int            y = 3;
  54.  
  55.    x = x.multiply(x,y);  // Notice that x is used both as an integer, and
  56.                          // as a class.
  57.  
  58.    printf("The value of x is %d.\n",x);
  59.  
  60.    return 0;
  61. }
  62.  
  63. /*----------------------------------------------------------------------------*/
  64.