回顾:
什么时候用引用返回,什么时候用传值返回,出了作用域变量还在就用引用返回,除了作用域变量销毁,则用传值返回


1. 日期类的比较大小操作符:(Date.h,函数声明)

写出其中两个,另外的四个都能写出来:
Date.cpp类:
bool Date::operator<(const Date& d)
{
if (_year < d._year)
{
return true;
}
else if (_year == d._year) {
if (_month < d._month)
{
return true;
}
else if (_month == d._month)
{
return _day < d._day;
}
}
return false;
}
bool Date::operator<=(const Date& d)
{
return *this < d || *this == d;
}
bool Date::operator>(const Date& d)
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
return !(*this < d);
}
bool Date::operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
bool Date::operator!=(const Date& d)
{
return !(*this == d);
}
2. 日期类的相减

两个日期类的相减,有两种思路,其中第二种要简单很多
//日期类的相减
// d1 - d2
int Date::operator-(const Date& d)
{
Date max = *this;
Date min = d;
int flag = 1; // 前一个数假设都是大的数
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
int day = 0;
while (min != max)
{
++day;
++min;
}
return day * flag;
}
3. 流输入输出重载
输出:
如果是函数声明在类内,会默认传一个形参this,而第一个参数默认是out,变成了d<<out


所以输入输出重载放在类外


类的成员变量设置成了private,访问不了,所以在类添加该函数为友元函数(这样就可以访问类中的成员变量了)

为了能够连续输出,必须返回out;

输入:
为了判断输入的日期是否正确,在日期类Date.h中添加检查函数

同样在Date.h的日期类中添加友元函数
Date.cpp:

Test.cpp



被折叠的 条评论
为什么被折叠?



