home *** CD-ROM | disk | FTP | other *** search
/ C++ for Dummies (3rd Edition) / C_FD.iso / CHAP23 / CHAP23_2.CPP < prev   
C/C++ Source or Header  |  1996-09-02  |  2KB  |  78 lines

  1. // Chap23_2.cpp
  2. #include <iostream.h>
  3. #include <iomanip.h>
  4. class Currency
  5. {
  6.   public:
  7.    Currency(double v = 0.0)
  8.    {
  9.       unit = v;
  10.       cent = int((v - unit) * 100.0 + 0.5);
  11.    }
  12.    virtual void display(ostream& out) = 0;
  13.  
  14.   protected:
  15.    unsigned int unit;
  16.    unsigned int cent;
  17. };
  18.  
  19. class USDollar : public Currency
  20. {
  21.   public:
  22.    USDollar(double v = 0.0) : Currency(v)
  23.    {
  24.    }
  25.    //display $123.00
  26.    virtual void display(ostream& out)
  27.    {
  28.       out << '$' << unit << '.'
  29.           << setfill('0') << setw(2) << cent
  30.           << setfill(' ');
  31.    }
  32. };
  33.  
  34. class DMark : public Currency
  35. {
  36.   public:
  37.    DMark(double v = 0.0) : Currency(v)
  38.    {
  39.    }
  40.    //display 123.00DM
  41.    virtual void display(ostream& out)
  42.    {
  43.       out << unit << '.'
  44.           //set fill to 0Æs for cents
  45.           << setfill('0') << setw(2) << cent
  46.           //now put it back to spaces
  47.           << setfill(' ')
  48.           << " DM";
  49.    }
  50. };
  51.  
  52. ostream& operator<< (ostream& o, Currency& c)
  53. {
  54.    c.display(o);
  55.    return o;
  56. }
  57.  
  58. void fn(Currency& c)
  59. {
  60.    //the following output is polymorphic because
  61.    //operator(ostream&, Currency&) is through a virtual
  62.    //member function
  63.    cout << "Deposit was " << c
  64.         << "\n";
  65. }
  66. int main()
  67. {
  68.    //create a dollar and output it using the
  69.    //proper format for a dollar
  70.    USDollar usd(1.50);
  71.    fn(usd);
  72.  
  73.    //now create a DMark and output it using its own format
  74.    DMark d(3.00);
  75.    fn(d);
  76.    return 0;
  77. }
  78.