一个无参构造函数,为当前日期创造一个Date对象
一个构造函数,按给出的自1970年1月1日0时流逝的秒数所指出的时间,创建一个Date对象
一个构造函数,创建一个给定year month day的Date对象
数据如year month day的三个get函数
一个成员函数setDate(int elapseTime),使用六十的秒数为对象设置新的日期
编写一个测试程序,它创建两个Date对象(分别使用Date()和Date(555550),然后输出他们的year month day
#include <iostream>
#include <ctime>
#include <iomanip>
class Date
{
public:
Date()
{
setDate(std::time(nullptr));
}
Date(std::time_t elapseTime)
{
setDate(elapseTime);
}
Date(int year, int month, int day) : _year(year), _month(month), _day(day) {}
int year() const { return _year; }
int month() const { return _month; }
int day() const { return _day; }
void setDate(std::time_t elapseTime)
{
auto tm = std::localtime(&elapseTime);
_year = tm->tm_year + 1900;
_month = tm->tm_mon + 1;
_day = tm->tm_mday;
}
private:
int _year;
int _month;
int _day;
};
std::ostream &operator<<(std::ostream &os, const Date &date)
{
os << date.year() << '-' << std::setw(2) << std::setfill('0') << date.month() << '-' << date.day();
return os;
}
int main()
{
Date date1, date2(555550);
std::cout << date1 << ' ' << date2 << std::endl;
return 0;
}