日期计算器
-
- Date类的规划
- Date类的实现
-
- Date 构造函数
- Date 拷贝构造函数
- ~Date 析构函数
- GetMonthDay 求某年某月的天数
- operator= 赋值操作符重载
- operator+= 加等操作符重载
- operator+ 加号操作符重载
- operator-= 减等操作符重载
- operator- 减法操作符重载 (日期 - 天数)
- operator++ 前置自增操作符重载
- operator++ 后置自增操作符重载
- operator-- 前置自减操作符重载
- operator-- 后置自减操作符重载
- operator< 小于操作符重载
- operator== 相等操作符重载
- operator!= 不等操作符重载
- operator<= 小于或等于操作符重载
- operator> 大于操作符重载
- operator>= 大于或等于操作符重载
- operator- 减法操作符重载(日期 - 日期)
- Print 打印函数
- Date 类的测试
概要
本篇主要探究C++ 实现日期计算器
Date类的规划
class Date
{
public:
int GetMonthDay(int year, int month);
Date(int year = 2024 , int month = 2, int day = 6);
Date(const Date& d);
Date& operator=(const Date& d);
~Date();
Date& operator+=(int day);
Date operator+(int day);
Date operator-(int day);
Date& operator-=(int day);
Date& operator++();
Date operator++(int);
Date operator--(int);
Date& operator--();
bool operator>(const Date& d) const;
bool operator==(const Date& d) const;
bool operator>= (const Date& d) const;
bool operator< (const Date& d) const;
bool operator<= (const Date& d) const;
bool operator!= (const Date& d) const;
int operator-(const Date& d) const;
void Print();
private:
int _year;
int _month;
int _day;
};
Date类的实现
Date 构造函数
Date::Date(int year, int month, int day)
:_year(year)
, _month(month)
, _day(day)
{
}
构造函数,他是在创建类的时候调用进行初始化操作,我们这里声明与定义分离,所以它的参数不需要填写缺省值,缺省值在声明的时候定义即可。
Date 拷贝构造函数
Date::Date(const Date& x)
:_year(x._year)
, _month(x._month)
, _day(x._day)
{
}
拷贝构造函数和构造函数作用相似,拷贝构造函数是将已有的类的对象拷贝给新创建的类的对象,如上所示。
~Date 析构函数
Date::~Date()
{
_year = _month = _day = 0;
}
构析函数是在对象即将销毁前所调用的函数,常用来清理数据空间,这里我们的内存都在栈上申请的,所以影响不大。
GetMonthDay 求某年某月的天数
int Date::GetMonthDay(int year,int month)
{
int a[13]={
0,31,28,31,30,31,30,31,31,30,31,30<