c++Design a class named MyDate. The class contains: The data fields year, month, and day that represent a date. month is 0-based, i.e., 0 is for January. A no-arg constructor that creates a MyDate object for the current date. A constructor that constructs a MyDate object with a specified elapsed time since midnight, January 1, 1970, in seconds. A constructor that constructs a MyDate object with the specified year, month, and day. Three constant get functions for the data fields year, month, and day, respectively. Three set functions for the data fields year, month, and day, respectively. A function named setDate(long elapsedTime) that sets a new date for the object using the elapsed time. Draw the UML for the class. Implement the class. Write a test program that creates two MyDate objects (using MyDate() and MyDate(343555551)) and displays their year, month, and day. (Hint: The first two constructors will extract the year, month, and day from the elapsed time. For example, if the elapsed time is 561555550 seconds, the year is 1987, the month is 9, and the day is 18.)
时间: 2024-03-05 15:48:28 浏览: 65
UML diagram:
```
+------------------------------------+
| MyDate |
+------------------------------------+
| -year: int |
| -month: int |
| -day: int |
+------------------------------------+
| +MyDate() |
| +MyDate(elapsedTime: long) |
| +MyDate(year: int, month: int, day: int)|
| +getYear(): int |
| +getMonth(): int |
| +getDay(): int |
| +setYear(year: int): void |
| +setMonth(month: int): void |
| +setDay(day: int): void |
| +setDate(elapsedTime: long): void |
+------------------------------------+
```
Implementation:
```cpp
#include <ctime>
class MyDate {
private:
int year;
int month;
int day;
public:
MyDate() {
time_t now = time(NULL);
struct tm t = *localtime(&now);
year = t.tm_year + 1900;
month = t.tm_mon;
day = t.tm_mday - 1;
}
MyDate(long elapsedTime) {
setDate(elapsedTime);
}
MyDate(int year, int month, int day) {
this->year = year;
this->month = month;
this->day = day;
}
int getYear() const {
return year;
}
int getMonth() const {
return month;
}
int getDay() const {
return day;
}
void setYear(int year) {
this->year = year;
}
void setMonth(int month) {
this->month = month;
}
void setDay(int day) {
this->day = day;
}
void setDate(long elapsedTime) {
time_t t = (time_t)elapsedTime;
struct tm* now = localtime(&t);
year = now->tm_year + 1900;
month = now->tm_mon;
day = now->tm_mday - 1;
}
};
int main() {
MyDate d1;
MyDate d2(343555551);
cout << d1.getYear() << " " << d1.getMonth() << " " << d1.getDay() << endl;
cout << d2.getYear() << " " << d2.getMonth() << " " << d2.getDay() << endl;
return 0;
}
```
阅读全文