操作符重载

本文介绍了一个C++中自定义日期类的实现,并详细展示了如何通过重载比较运算符来实现日期之间的比较。代码示例清晰地说明了如何创建日期对象以及如何使用这些重载的运算符来判断两个日期是否相等、前后顺序等。

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

#include<iostream>

using namespace std;

class  Date
{
public:
	int month, day, year;

public:
	Date(int m = 0, int d = 0, int y = 0) :month(m), day(d), year(y){}

	int operator==(Date& dt)const;
	int operator!=(Date& dt)const;

	//应该把所有的关系操作符一起重载

	int operator<(Date&  dt)const;
	int operator>(Date&  dt)const;
	int operator<=(Date&  dt)const;
	int operator>=(Date&  dt)const;

};

int Date::operator==(Date& dt) const
{
	return ((this->month == dt.month) && (this->day == dt.day) && (this->year == dt.year));
}
int Date::operator!=(Date& dt)const
{
	return !(*this == dt);//一起重载,一种关系运算符取操作另外一种关系运算符
	//不等于转去调用==
}



int Date::operator<(Date& dt) const
{
	if (this->year == dt.year)
	{
		if (this->month == dt.month)
			return this->day < dt.day;
		return this->month < dt.month;
	}
	return this->year < dt.year;
}
 
int main()
{
	
	Date d1(2, 14, 2015);
	Date d2(6, 19, 2015);
	Date d3(2, 14, 2015);

	if (d1 < d2)
	{
		cout << "d1小于d2" << endl;
	}
	if (d1 == d3)
	{
		cout << "OK" << endl;
	}

	cout << "asdhu adas d" << endl;

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值