1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
#include <iostream>
#include <iomanip>
using namespace std;
// class declaration section
class Date
{
private:
int month, day, year;
public:
Date(int = 7, int = 4, int = 2005); // constructor
Date(long); // type conversion constructor
Date operator+(int); // overload the + operator
Date operator-(int);
void showDate();
};
// class implementation section
// constructor
Date::Date(int mm, int dd, int yyyy)
{
month = mm;
day = dd;
year = yyyy;
}
// type conversion constructor from long to Date
Date::Date(long findate)
{
year = int(findate/10000.0);
month = int((findate - year * 10000.0)/100.0);
day = int(findate - year * 10000.0 - month * 100.0);
}
Date Date::operator+(int days)
{
Date temp; // a temporary date to store the result
temp.day = day + days; // add the days
temp.month = month;
temp.year = year;
while (temp.day > 30) // now adjust the months
{
temp.month++;
temp.day -= 30;
}
while (temp.month > 12) // adjust the years
{
temp.year++;
temp.month -= 12;
}
return temp; // the values in temp are returned
}
Date Date::operator-(int days)
{
Date temp; // a temporary date to store the result
temp.day = day - days; // subtract the days
temp.month = month;
temp.year = year;
while (temp.day > 30) // now adjust the months
{
temp.month++;
temp.day -= 30;
}
while (temp.month > 12) // adjust the years
{
temp.year++;
temp.month -= 12;
}
return temp; // the values in temp are returned
}
// member function to display a date
void Date::showDate()
{
cout << setfill('0')
<< setw(2) << month << '/'
<< setw(2) << day << '/'
<< setw(2) << year % 100;
return;
}
int main()
{
Date a, b(20061225L), c(4,1,2007); // declare 3 objects and
// initialize 2 of them
cout << "Dates a, b, and c are ";
a.showDate();
cout << ", ";
b.showDate();
cout << ", and ";
c.showDate();
cout << ".\n";
a = Date(20080103L); // cast a long to a Date
cout << "Date a is now ";
a.showDate();
cout << "The initial date is ";
a.showDate();
cout << endl;
b = a + 284; // add in 284 days = 9 months and 14 days
cout << "The new date is ";
b.showDate();
cout << endl;
cout << ".\n";
a = Date(20080103L); // cast a long to a Date
cout << "Date a is now ";
a.showDate();
cout << "The initial date is ";
a.showDate();
cout << endl;
b = a - 284; // add in 284 days = 9 months and 14 days
cout << "The new date is ";
b.showDate();
cout << endl;
cout << ".\n";
return 0;
}
|