Date日期类应该是好多学c++类或者开始学c++时,第一份比较重要的代码吧,当时刚接触c++,的确一开始学的有些不易,在自己敲date日期类这个代码的时候有一些不懂得地方也自己琢磨了一些时间。所以,我把自己的代码贴出来,尽量做到详细解读,希望对看到的人有些帮助,也同时对我自己是个回顾吧。
-
先提前说一下,我这次的代码只有一个.h和一个.cpp。我只在.cpp中调用.h中的测试函数,所以我的.h包含这个date日期类的全部代码。
-
先给出类的定义,然后在给出具体实现吧。一般我们写代码,也是先写出基本框架,然后在由粗至细吧,看别人代码也是一个道理,先看框架然后在看具体实现的细节。
class Date
{
friend ostream& operator<<(ostream& _cout, const Date& date);
friend istream& operator>>(istream& _cin, Date& date);
public:
int GetDay(int year, int month);
Date(int year = 1900, int month = 1, int day = 1);
Date(const Date& date);
Date& operator=(const Date& date);
bool operator>(const Date& d);
bool operator<(const Date& d);
bool operator==(const Date& d);
bool operator!=(const Date& d);
bool operator>=(const Date& d);
bool operator<=(const Date& d);
Date operator+(int day);
Date operator-(int day);
Date operator++();
Date operator++(int);
Date operator--();
Date operator--(int);
int operator-(const Date&d);
private:
int _year;
int _month;
int _day;
};
基本的c++概念我就不详细解读了,从代码角度切入吧,先说它两:
ostream& operator<<(ostream& cout, const Date& date)
{
cout << date._year << "-" << date._month << "-" << date._day;
return cout;
}
istream& operator>>(istream& cin, Date& date)
{
cin >> date._year >> date._month >> date._day;
return cin;
}
- 还是先举个例子吧
cout<<d1
,这个d1
是Date
类型的,也就是自定义类型。但是cout只能输出内置类型,也就是int,char
这些类型的数据。那怎么才能通过cout输出自定义类型的数据呢。我们首先肯定想到的是重载,但是!cout的输出流对象和隐含的this指针在抢占第一个参数的位置。可是实际使用中cout
需要是第一个形参对象,才能正常使用。所以我们要将operator<<
重载成全局函数。但是这样的话,又会导致类外没办法访问成员,那么这里就需要友元来解决。也就是上边的这段码。这样我们就可以输出和输入自定义类型的数据了。
友元函数可以直接访问类的私有成员,它是定义在类外部的普通函数,不属于任何类,但需要在类的内部声明,声明时需要加
friend
关键字。
然后是构造和拷贝构造函数,以及构造函数中会调用的GetDay函数:
int GetDay(int year, int month)
{
static int _Day[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2
&& (year % 4 == 0 && year % 100 != 0
|| year % 400 == 0))
return 29;
else
return _Day[month];
}
Date(int year = 1900, int month = 1,