C++——类和对象3 日期类型 Cout运算符重载 Cin运算符重载 const成员 _cout对象的重载(3)

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

cout << ret5 << endl;
return 0;

}


 ![](https://img-blog.csdnimg.cn/32b9cb36c5de480c99176949f7c9ce6c.png)



> 
>  一个类到底可以重载哪些运算符,要看哪些运算符对这个类型有意义
> 
> 
> 日期减天数思路:先给天减,如果不够(<=0)就借位
> 
> 
> 程序有缺陷,构造这里出现了问题
> 
> 
> ![](https://img-blog.csdnimg.cn/2ff28ee55fc942e391e3096b614a1347.png)
> 
> 
> 我们在类里面加上判断日期的函数即可或者用assert去判
> 
> 
> 
> ```
> 	Date(int year = 1900, int month = 1, int day = 1)
> 	{
> 		_year = year;
> 		_month = month;
> 		_day = day;
>          //assert(CheckDate());
> 		if (!CheckDate())
> 		{
> 			Print();
> 			cout << "日期非法" << endl;
> 		}
> 	}
> 	bool CheckDate()
> 	{
> 		if (_year >= 1 && _month < 13 && _month>0 && _day > 0 && _day <= GetMonthDay(_year, _month))
> 			return true;
> 		else
> 			return false;
> 	}
> ```
> 
>                 ![](https://img-blog.csdnimg.cn/95008d8119c84c05889f1c5a29ff57a8.png)      
> 
> 
> 加一个负数会报错,我们只需在+=里面进行调整就行,因为+是通过+=实现的
> 
> 
> 
> 
> 
> ```
> Date&  Date::operator+=(int day)
> {
> 	if (day < 0)
> 	{
> 		return *this -= -day;
> 	}
> 	_day += day;
> 	while (_day > GetMonthDay(_year, _month))
> 	{
> 		_day -= GetMonthDay(_year, _month);
> 		_month++;
> 		if (_month == 13)
> 		{
> 			_month = 1;
> 			_year ++;
> 		}
> 	}
> 	return *this;
> }
> ```
> 
> ![](https://img-blog.csdnimg.cn/743d0277c0bf406fa6c48c7f3bc8cdf5.png)
> 
> 
>  ![](https://img-blog.csdnimg.cn/0e0af85c8582408e8260ae6c2e86a3b0.png)![](https://img-blog.csdnimg.cn/ac126feef57046729573a65530a3c044.png)
> 
> 
> 
> 同理对-=也修改,如果天数小于0,-=之后 会因为负负得正,给加几天,我们此时调整一下即可
> 
> 
> 


## 实现Cout运算符重载



> 
> 
> C++ cout和cin能自动识别的原因:
> 
> 
> 1.库里面写好了运算符重载
> 
> 
> 2.自动识别类型,它们构成重载函数 
> 
> 
> ![](https://img-blog.csdnimg.cn/5755a81e42294300991494b2ca2b9046.png)
> 
> 
> 运算符重载:让自定义类型对象可以用运算符,转换成调用这个重载函数
> 
> 
> 函数重载:支持函数名相同的函数同时存在
> 
> 
> 虽然俩者都是重载,但它们俩者没有关系
> 
> 
> 但如果这样使用cout和cin会报错
> 
> 
> ![](https://img-blog.csdnimg.cn/06ce98140e5841fd974a6ddc6621874e.png)
> 
> 
>  此时我们自己在类里面写运算重载符就可以解决这个问题
> 
> 
> cout是ostream类型对象,cin是istream类型对象
> 
> 
> 
> ```
> void Date::operator<<(ostream& out)
> {
> 	out << _year << "-" << _month << _day;
> }
> ```
> 
> 此时如果写成这个样子,还是会报错
> 
> 
> ![](https://img-blog.csdnimg.cn/513ae5dc84714e0eb3ec959ce4892383.png)
> 
> 
> 但这样可以
> 
> 
> ![](https://img-blog.csdnimg.cn/11897c495810404fa3dd7a452121b3cc.png)
> 
> 
>  运算符有多个操作数的时候,第一个参数是左操作数,第二个参数是右操作数
> 
> 
> ![](https://img-blog.csdnimg.cn/2befdbc3d69a46af943bb8b84c402414.png)
> 
> 
> d1是第一个操作数(左操作数),cout是第二个操作数 (右操作数)
> 
> 
> cout<<d1转换为cout.operatpr(d1),所以会报错
> 
> 
> 若想通过cout<<d1来打印,则不能修改上面的运算符重载,因为类对象抢占了第一个数,默认是this,所以无法通过修改运算符重载来实现该语句
> 
> 
> 
> 此时把该运算符重载写到外面,当作一个函数,不能当成员函数使用,out就会是第一个操作数
> 
> 
> ![](https://img-blog.csdnimg.cn/c6632dd825e742c19ce2db34c22356ec.png)
> 
> 
>  但会有一个缺陷,私有变量无法访问
> 
> 
> ![](https://img-blog.csdnimg.cn/29b1aa710c424d61b3aebed2d70f75ad.png)
> 
> 
>  这里可以通过友元进行修改
> 
> 
> ![](https://img-blog.csdnimg.cn/8fdc4d03bebb4821a426a682265482f4.png)
> 
> 
> 此时就可以访问这些私有成员
> 
> 
> ![](https://img-blog.csdnimg.cn/117b551b547245c4baf95e997f912d09.png)
> 
> 
>  但此时这样写又会不支持
> 
> 
> ![](https://img-blog.csdnimg.cn/f6f63a7d31104786bc9d24e3ecb988af.png)
> 
> 
>  这里需要返回值,返回值就是cout,这样才能连续的插入
> 
> 
> 
> ![](https://img-blog.csdnimg.cn/e51b479076f9486188a5115d3cb82bfc.png)
> 
> 
> 此时可正常打印
> 
> 
> ![](https://img-blog.csdnimg.cn/545314c5290243b48091008c679e58c7.png)
> 
> 
> ![](https://img-blog.csdnimg.cn/dafa040db24c4c8a89e16709790595b1.png)
> 
> 
> 
> ![](https://img-blog.csdnimg.cn/aee01f94a4da45d8a672432212d74d3d.png)
> 
> 
>  这个函数可能会被频繁调用,可能输出多行,因此搞成内联函数最好
> 
> 
> ![](https://img-blog.csdnimg.cn/df86f2be53fc4662b26a7556b9801bdf.png)
> 
> 
>  但是此时声明在.h定义在.cpp,声明和定义分离,链接时报错
> 
> 
> ![](https://img-blog.csdnimg.cn/f7c5189621df46f98ed91fb50905ae40.png)
> 
> 
> 直接在.h里面定义好就行 
> 
> 
> 


## 实现Cin运算符重载



> 
> cin是istream类型对象,流提取,cout不需要改变Date,但Cin需要改变Date
> 
> 
> 因为这是要从流里面提取出年月日参数,放到日期里面
> 
> 
> ![](https://img-blog.csdnimg.cn/f864c176720f4b0395af877422c0528e.png)
> 
> 
>  ![](https://img-blog.csdnimg.cn/62bb5691c97c4911a66a097ef63561ae.png)
> 
> 
> 但此时输入非法日期不报错
> 
> 
> ![](https://img-blog.csdnimg.cn/4f1cb18e5df8421c803845aaf074b0cc.png) 此时在加个判断
> 
> 
> ![](https://img-blog.csdnimg.cn/94273345ecde4ba381fc2ace89ed3f57.png)
> 
> 
> 
> 
> 
> 


### 根据日期算星期



> 
>  以1年1月1日星期六为参考对象,输入一个日期后,俩日期相减,然后对7取模就行
> 
> 
> 0相当于周天,1-5对应周一到周六
> 
> 
> 
> ```
> void DateSwap()
> {
> 	const char* WeekDayToStr[] = { "周一","周二","周三","周四","周五","周六","周日" };
> 	Date d1;
> 	Date start(1, 1, 1);
> 	cout << "请输入日期";
> 	cin >> d1;
> 	int n = d1 - start;
> 	int weekDay = 0;
> 	weekDay += n;
> 	cout << WeekDayToStr[ weekDay % 7] << endl;
> }
> ```
> 
> 


## 修改后完整代码


### Date.h



#include
#include<assert.h>
using namespace std;
class Date
{
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
// 获取某年某月的天数
int GetMonthDay(int year, int month)
{
static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = days[month];
if (month == 2
&& ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
{
day += 1;
}
return day;
}
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
if (!CheckDate())
{
Print();
cout << “日期非法” << endl;
}
}
bool CheckDate()
{
if (_year >= 1 && _month < 13 && _month>0 && _day > 0 && _day <= GetMonthDay(_year, _month))
return true;
else
return false;
}
void Print();
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++();//默认是前置++,返回+完后的值,用引用返回
Date operator++(int i);//后前置++,里面要写一个参数,这里的参数可以不用形参接收,括号里直接写int就行,但加了参数也无所谓,这里的参数只是为了区分
//C++为了区分前后置++,使用重载进行区分,后置++重载增加一个int参数跟前置构成函数重载进行区分
Date& operator+=(int day);
Date operator-(int day);
Date& operator-= (int day);
Date& operator–();
Date operator–(int);
int operator-(const Date& d);

private:
int _year;
int _month;
int _day;
};
inline ostream& operator<<(ostream& out, const Date& d)
{
out << d._year <<“年” << d._month<< “月” << d._day<<“日” << endl;
return out;
}
inline istream& operator>>(istream & in, Date & d)
{
assert(d.CheckDate());
in >> d._year >> d._month >> d._day;
return in;
}
void DateSwap();


### Date.cpp



#include"date.h"
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);
}
bool Date::operator>(const Date& d)
{
if (_year > d._year)
return true;
else if (_year == d._year && _month > d._month)
{
return true;
}
else if (_year == d._year && _month == d._month && _day > d._day)
{
return true;
}
else
return false;
}
bool Date::operator<(const Date& d)
{
return !(*this >= d);
}
bool Date::operator>=(const Date& d)
{
return (*this > d) || (*this == d);
}
bool Date::operator<=(const Date& d)
{
return !(*this > d);
}
// 自身要改变
Date& Date::operator+=(int day)
{
if (day < 0)
{
return *this -= -day;
}
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13)
{
_month = 1;
_year ++;
}
}
return *this;
}
//自身不改变
Date Date::operator+(int day)
{
Date ret(*this);//拷贝构造
//Date ret= this;在这里,这条语句是拷贝构造,拿this初始化ret,已经存在的对线才是赋值
ret += day;
return ret;//传值返回的时候,会生成一份拷贝
}
void Date::Print()
{
cout << _year<<“/” << _month<<“/”<<_day << endl;
}
Date& Date::operator++()//前置
{
*this += 1;
return *this;
}
Date Date::operator++(int)//后置,返回++之前的值
{
Date tmp(*this);
*this += 1;
return tmp;
}
Date& Date::operator-= (int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day <= 0)
{
–_month;
if (_month == 0)
{
–_year;
_month = 12;
}
_day += GetMonthDay(_year,_month);
}
return *this;
}
Date Date::operator-(int day)
{
Date ret = *this;
ret -= day;
return ret;
}
Date& Date::operator–()//前置–
{
*this -= 1;
return *this;
}
Date Date::operator–(int)//后置–
{
Date tmp = *this;
*this -= 1;
return tmp;
}
int Date::operator-(const Date& d)//日期相减
{
int flag = 1;
Date max = *this;
Date min = d;
if (this < d)
{
min = this;
max = d;
flag = -1;
}
int n = 0;
while (min != max)
{
++min;
++n;
}
return n
flag;
}
void DateSwap()
{
const char
WeekDayToStr[] = { “周一”,“周二”,“周三”,“周四”,“周五”,“周六”,“周日” };
Date d1;
Date start(1, 1, 1);
cout << “请输入日期”;
cin >> d1;
int n = d1 - start;
int weekDay = 0;
weekDay += n;
cout << WeekDayToStr[ weekDay % 7] << endl;
}

//void Date::operator<<(ostream& out)
//{
// out << _year << “-” << _month <<“-” << _day;
//}


## const成员



> 
>  ![](https://img-blog.csdnimg.cn/a39e072b3d224b68b414ac9a9da04ad6.png)
> 
> 
> 这种情况下会报错 ,会把const Date转换为Date
> 
> 
> 这是因为this指针在传参的时候是这样的
> 
> 
> ![](https://img-blog.csdnimg.cn/be0192e49f8f4b569592f6e04fec70ff.png)
> 
> 
> 参数里的const修饰this指针本身 
> 
> 
> d1.Print();传参的时候是将d1的地址传过去,&d1,类型是Date\*
> 
> 
> d2.Print();&d2 传不过去,因为传过去的是const Date\*类型,而形参是Date\*类型
> 
> 
> ![](https://img-blog.csdnimg.cn/cb6582a77e6a4e1b8e32bb8744e63d47.png)
> 
> 
> d1<d2可以,d2<d1不可以
> 
> 
>  ![](https://img-blog.csdnimg.cn/6febb869e4de45eba96d207a89805892.png)
> 
> 
>  d1<d2,d1是Date \*可以传过去
> 
> 
> d2<d1,d2是const Date \*不能传给this,所以会报错
> 
> 
> 如果要改变这种错误,就要给this加上const,Date \*const this变为const Date \*const this
> 
> 
> 把const加在这个位置
> 
> 
> ![](https://img-blog.csdnimg.cn/c0dbd56acbee435997416fac72a93e57.png)
> 
> 


![img](https://img-blog.csdnimg.cn/img_convert/d14cdb54ffb2eee930b761eff8d56744.png)
![img](https://img-blog.csdnimg.cn/img_convert/9d7041390fb052f0f26d33646e19c06b.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618668825)**

febb869e4de45eba96d207a89805892.png)
> 
> 
>  d1<d2,d1是Date \*可以传过去
> 
> 
> d2<d1,d2是const Date \*不能传给this,所以会报错
> 
> 
> 如果要改变这种错误,就要给this加上const,Date \*const this变为const Date \*const this
> 
> 
> 把const加在这个位置
> 
> 
> ![](https://img-blog.csdnimg.cn/c0dbd56acbee435997416fac72a93e57.png)
> 
> 


[外链图片转存中...(img-9SCK9BSu-1715735738693)]
[外链图片转存中...(img-zo1H2fN2-1715735738693)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上C C++开发知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618668825)**

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值