home *** CD-ROM | disk | FTP | other *** search
/ C++ for Dummies (3rd Edition) / C_FD.iso / CHAP21 / CHAP21_3.CPP < prev   
C/C++ Source or Header  |  1996-09-02  |  580b  |  29 lines

  1. // Chap21_3.cpp
  2. class USDollar
  3. {
  4.   public:
  5.    USDollar(double value = 0.0);
  6.    //the following function acts as a cast operator
  7.    operator double()
  8.    {
  9.       return dollars + cents / 100.0;
  10.    }
  11.   protected:
  12.    unsigned int dollars;
  13.    unsigned int cents;
  14. };
  15. USDollar::USDollar(double value)
  16. {
  17.     dollars = (int)value;
  18.     cents = (int)((value - dollars) * 100 + 0.5);
  19. }
  20. int main()
  21. {
  22.    USDollar d1(2.0), d2(1.5), d3;
  23.    //invoke cast operator explicitly...
  24.    d3 = USDollar((double)d1 + (double)d2);
  25.    //...or implicitly
  26.    d3 = d1 + d2;
  27.    return 0;
  28. }
  29.