home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 13 / CDA13.ISO / cdactual / demobin / share / program / C / ANSICPP.ZIP / EX08002.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1990-07-24  |  802 b   |  40 lines

  1. // ex08002.cpp
  2. // Overloading the + operator with a friend
  3. #include <iostream.h>
  4.  
  5. class Date {
  6.     int mo, da, yr;
  7. public:
  8.     Date() {}
  9.     Date(int m, int d, int y) { mo = m; da = d; yr = y; }
  10.     void display() { cout << mo << '/' << da << '/' << yr; }
  11.     // ----- overloaded + operators
  12.     Date operator+(int);
  13.     friend Date operator+(int n, Date& dt) { return dt + n;}
  14. };
  15.  
  16. static int dys[] = {31,28,31,30,31,30,31,31,30,31,30,31};
  17. // -------- overloaded + operator
  18. Date Date::operator+(int n)
  19. {
  20.     Date dt = *this;
  21.     n += dt.da;
  22.     while (n > dys[dt.mo-1])    {
  23.         n -= dys[dt.mo-1];
  24.         if (++dt.mo == 13)    {
  25.             dt.mo = 1;
  26.             dt.yr++;
  27.         }
  28.     }
  29.     dt.da = n;
  30.     return dt;
  31. }
  32.  
  33. main()
  34. {
  35.     Date olddate(2,20,90);
  36.     Date newdate;
  37.     newdate = 21 + olddate;    // three weeks hence
  38.     newdate.display();
  39. }
  40.