CS 1440 Lab 8
· Continued practice with C++ classes
1. First, we'll look at a main function that uses Dates.
2. Then, we'll define the Date class.
3. Then, we'll begin implementing the Date class.
1. Main -- client of our Date class
Look over this main function that uses Dates.
Date today; /* Creates Date object */
int d, m, y;
cout << "Enter month: ";
cin >> m;
cout << "Enter day: ";
cin >> d;
cout << "Enter year: ";
cin >> y;
/* Some member function calls */
today.set(m,d,y); /* Sets object data members */
today.ShortDisplay(); /* Displays: dd/mm/yyyy */
cout << endl;
today.LongDisplay(); /* Displays: dd Month yyyy */
cout << endl;
2. Defining the Date class
We know that a Date keeps track of month, day, and year. So, we'll need some data members for these. (If we wanted a really great Date class we could have another data member for day of week, but we won't worry about that now!) From seeing our client, we need some member functions: set, LongDisplay, and ShortDisplay. So, let's define it!
If you're brave, try defining it on your own first -- then compare yours with the one below.
void set(int m, int d, int y);
int day, month, year;
3. Implementing the Date class
Now, we need to actually write the functions that the class definition only prototypes. Remember that you need to connect your function definition to the prototype in the class definition by preceding the function name with the class name and the :: symbol.
void Date::set(int m, int d, int y)
/* Set "my" data members with values
passed in from client as parameters. */
year = y;
day = d;
month = m;
/* Display as: mm/dd/yyyy
for example: 3/31/2002 */
/* YOU DO IT!! */
/* Display as: dd Month yyyy
for example: 31 March 2002 */
cout << day;
if (month == 1) cout << " January ";
else if (month == 2) cout << " February ";
else if (month == 3) cout << " March ";
else if (month == 4) cout << " April ";
else if (month == 5) cout << " May ";
else if (month == 6) cout << " June ";
else if (month == 7) cout << " July ";
else if (month == 8) cout << " August ";
else if (month == 9) cout << " September ";
else if (month == 10) cout << " October ";
else if (month == 11) cout << " November ";
else if (month == 12) cout << " December ";
else cout << "UnknownMonth";
cout << year;
Cut and the paste the above pieces of code into a file called Act2.C. (Be careful to put the class definition before the main function.)
Finish implementing the Date::ShortDisplay function.
Make sure you include the necessary headers, and add a comment block.
Verify your program works by compiling and running it.