c++ 运算符重载 实现时间的加减

class time
{
	private :
	int hour;
	int minute;
	int second;
	public :
	time(){ hour=0;minute=0;second=0;}//定义构造函数
	time( int h, int m, int s){ hour=h; minute=m; second=s;}//定义构造函数的重载
	time operator + (time & t2);//声明重载运算符'+'的函数
	time operator - (time & t2);//声明重载运算符'+'的函数
	void display();
};
time time :: operator +(time & t2)
{
	time t;
	t.second=second + t2.second;
	if (t.second >=60)
	{
		t.second= t.second - 60;
	t.minute =t.minute + 1;
	}
	
	t.minute = minute +t2.minute;
	if (t.minute >=60)
	{
	t.minute = t.minute - 60;
	t.hour = t.hour + 1;
	}
	t.hour = hour +t2.hour;
	if( t.hour >= 24)
	t.hour = 00;
	return t;
}

time time :: operator -(time & t2)
{
	time t;
	t.second=second - t2.second;
	if (t.second < 0)
	{
		t.second= 60 + t.second;
	t.minute =t.minute - 1;
	}
	
	t.minute = minute - t2.minute;
	if (t.minute < 0)
	{
	t.minute = 60 + t.minute ;
	t.hour = t.hour - 1;
	}
	t.hour = hour - t2.hour;
	if( t.hour < 0)
	t.hour = 23 + hour ;
	return t;
}
void time :: display()
{
	cout <<"("<<hour<<':'<<minute<<":"<<second<<")"<<endl;	
	}
int main()
{  
	time t1(3,3,4),t2(2,2,2),t3,t4;
	t3 = t1 + t2; 
	cout<<"t1+t2=";t3.display();
	t4 = t1 - t2; 
	cout<<"t1-t2=";t4.display();
	return 0;
}
	

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值