
type(返回类型) operator (需要重载的运算符)(参数)
{
}// 使用这些函数时记得包含<stdio.h>或<iostream>文件
// 将日期写入文件
// 打开文件
FILE* pf1 = fopen("Date.txt","w");
// 判断文件是否成功打开
if (pf1 == NULL)
{
perror("fopen fail");
}
// 将值写入文件
fprintf(pf1,"%d\n",2024);
fprintf(pf1,"%2d\n", 1);
fprintf(pf1,"%2d\n", 1);
fclose(pf1);
// 从文件中读取日期
FILE* pf2 = fopen("Date.txt", "r");
if (p2 == NULL)
{
perror("fopen fail");
}
int year = 0, month = 0, day = 0;
// 读取文件并将读取到的值传入地址
fscanf(pf2,"%d",&year);
fscanf(pf2, "%2d",&month);
fscanf(pf2, "%2d",&day);
printf("%2d // %2d // %2d",year,month,day);
fclose(pf1);// 一三五七八十腊,三十一天永不差。0
// 平年二月二十八,闰年二月二十九。
// 闰年:四的倍数或者四百的倍数。
// 但不是一百和四共同的的倍数。
//
int GetMonthDay(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;
}
return day[month];
}// 全缺省的构造函数
//(注意除上面确定月份的天数的代码在类和对象中定义,
// 下面的代码都是申明(类域内)与定义(类域外)分开的)
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
// 拷贝构造函数
// d2(d1)
Date::Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
// 由于变量中没有向堆申请空间,或是带有其他资源,所以不需要写析构函数
// 析构函数
Date::~Date()
{
}// 第一种运算符重载的使用方法
Date d1,d2;
d1.operator = d2
// 第二种运算符重载的使用方法
d1 = d2;// 等于运算符重载
Date& Date::operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}//前置加加(另外尽量用引用返回减少不必要的拷贝,节约时间)
Daate& operator ++ (); // ++a(立马加一)
//后置++,用一个int充当标识符,区分后置与前置++
Date operator ++ (int); // a++(执行完当前代码再加一)// 运算符 +=
Date& Date::operator+=(int day)
{
_day += day;
while (_day > GetMonthDay(_year,_month))
{
_day -= GetMonthDay(_year,_month);
_month++;
if (_month == 13)
{
_year++;
_month = 1;
}
}
return *this;
}// 前置++
Date& Date::operator++()
{
Date tmp = *this;
*this += 1;
return tmp;
}
// 后置++
Date Date::operator++(int)
{
*this += 1;
return *this;
}// 最高位先进行比较,等于就看下一位,有一位大于返回true
bool Date::operator >= (const Date& d)
{
if (_year < d._year)
{
return false;
}
if (_year == d._year)
{
if (_month < d._month)
{
return false;
}
if (_month == d._month)
{
if (_day < d._day)
{
return false;
}
}
}
return true;
}// ==运算符重载
bool Date::operator==(const Date& d)
{
return _year == d._year &&
_month == d._month &&
_day == d._day;
}