【C++初阶】ostream&、operater<<、operator<<(ostream& _cout, const Date& d)、bool引导的结构体内嵌比较函数解析

文章详细介绍了C++中日期类(Date)如何重载比较运算符operator<()和operator>(),以及友元函数operator<<(ostream&,constDate&)的实现。这两个运算符用于比较日期的先后,而友元函数则支持将日期对象输出到标准输出流。const关键字在这里用于确保参数对象不被修改,并且在const成员函数中使用,表示函数不会修改类的任何成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 对C++重载、判断部分的知识进行梳理 

目录

一、bool operator>(const Date& d) const【bool引导的结构体内嵌比较函数】

1.代码整体含义

2.代码两个const的含义

二、friend ostream& operator<<(ostream& _cout, const Date& d)

1. 相关基础概念 

2. 三个引用&


问题来源于下面这个日期类

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}
	bool operator<(const Date& d)const
	{
		return (_year < d._year) ||
			(_year == d._year && _month < d._month) ||
			(_year == d._year && _month == d._month && _day < d._day);
	}
	bool operator>(const Date& d)const
	{
		return (_year > d._year) ||
			(_year == d._year && _month > d._month) ||
			(_year == d._year && _month == d._month && _day > d._day);
	}
	friend ostream& operator<<(ostream& _cout, const Date& d)
	{
		_cout << d._year << "-" << d._month << "-" << d._day;
		return _cout;
	}
private:
	int _year;
	int _month;
	int _day;
};



int main()
{
    Date date;
    cout<<date<<endl;
}

一、bool operator>(const Date& d) const【bool引导的结构体内嵌比较函数】

1.代码整体含义

我们可以截取一段代码进行解析

b
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值