C++面向对象函数重载

设计一个日期类Date,该类包含数据成员 year(年),month(月),day(日),定义构造函数。
要求: (1)重载日期加上天数的加法运算符+ (例如 给一个日期加上10天);
(2) 重载日期的自增运算符++ ;(需要满30进一天)。

#include<iostream>
using namespace std;

class Date
{
	public:
		Date(){year=0;month=0;day=0;}
		Date(int y,int m,int d):year(y),month(m),day(d){}
		void display();
		Date operator+(int num);
		Date operator++();//前置++ 
		Date operator++(int);//后置++,与前置++区分,系统默认加上int
	private:
		int year;
		int month;
		int day;
};

void Date::display()
{
	cout<<year<<"/"<<month<<"/"<<day;
}

Date Date::operator+(int num)
{
	int flag=1;
	day=day+num;
	while(flag)
	{
		if(day>=30)
		{
			month++;
			day=day-30;
			if(month>=12)
			{
				year++;
				month=1;
			}
		}
		if(day<30)	flag=0;
	}
	return Date(year,month,day);
}

Date Date::operator++()
{
	day++;
	if(day>=30)
	{
		month++;
		day=1;
		if(month>=12)
		{
			year++;
			month=1;
		}
	}
	return Date(year,month,day);
}

Date Date::operator++(int)
{
	day++;
	if(day>=30)
	{
		month++;
		day=1;
		if(month>=12)
		{
			year++;
			month=1;
		}
	}
	return Date(year,month,day);
}

int main()
{
	Date d1(2018,11,13),d2;
	d1.display();
	cout<<"+100:";
	d2=d1+100;
	d2.display();
	cout<<endl;
	
	cout<<"++";
	d1.display();cout<<": ";
	d2=++d1;
	d2.display();
	cout<<endl;
	
	d1.display();
	cout<<"++: "; 
	d2=d1++;
	d2.display();
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值