C++周四作业

文章介绍了C++中一个名为ttime的自定义时间类,包括构造函数、成员函数,如加法、减法运算以及对时间分段的访问。展示了如何使用这个类进行时间的计算和显示。
摘要由CSDN通过智能技术生成
题目:

代码实现:
#include<iostream>

using namespace std;

class ttime
{
	public:
	ttime()
	{
		h = 0;
		m = 0;
		s = 0;
	}
	ttime(int xh,int xm,int xs ) 
	{
		h = xh;
		m = xm;
		s = xs;
	}
	int &operator[](int i);
	ttime operator+(ttime tm1);
	ttime operator-(ttime tm1);
	ttime operator-(int n);
	ttime operator+(int i)
	private:
	int h;
	int m;
	int s;
	int flag = -1;
};

int &ttime::operator[](int i)
	{
		if(i == 0)
		{
			return h;
		}
		else if(i == 1)
		{
			return m;
		}
		else if(i == 2)
		{
			return s;
		}
		else
		{
			cout<<"下标错误"<<endl;
			return flag;
		}
	
	}
	
ttime ttime::operator+(ttime tm1)
{
	ttime tm2;
	tm2.s = this->s + tm1.s;
	if(tm2.s >=60)
	{
		tm2.s -= 60;
		tm2.m += 1;
	}
	tm2.m = this->m + tm1.m + tm2.m;
	if(tm2.m>=60)
	{
		tm2.m -= 60;
		tm2.h += 1;
	}
	tm2.h = this->h + tm1.h + tm2.h;
	
	return tm2;
}

ttime ttime::operator-(ttime tm1)
{
	ttime tm2;
	tm2.s = this->s - tm1.s;
	if(tm2.s < 0)
	{
		tm2.s += 60;
		tm2.m -= 1;
	}
	tm2.m = this->m - tm1.m + tm2.m;
	if(tm2.m < 0)
	{
		tm2.m += 60;
		tm2.h -= 1;
	}
	tm2.h = this->h - tm1.h + tm2.h;
	if(tm2.h < 0)
	{
		cout<<"时间不够减啦!!!"<<endl;
	}
	return tm2;
}

ttime ttime::operator-(int n)
{
	this->s -=n;
	which(1)
	{
	if(this->s < 0)
	   {
			this->s += 60;
			this->m -=1;
	   }
	   if(this->s > 0)
	   {
		   break;
	   }
	}
	which(1)
	{
	if(this->m < 0)
	   {
			this->m += 60;
			this->h -= 1;
	   }
	   if(this->m>0)
	   {
		   break;
	   }
	}
	if(this->h < 0)
	{
		cout<<"时间不够减啦!!!"<<endl;
	}
	return this;
	
}
ttime ttime::operator+(int i)
{
	this->s += i;
	which(1)
	{
	if(this->s >= 60)
		{
			this->s -= 60;
			this->m += 1;
		}
	if(this->s <60)
		{
			break;
		}
	}
	which(1)
	{
	if(this->m >= 60)
		{
			this->m -= 60;
			this->h += 1;
		}
	if(this->m <60)
		{
			break;
		}
	}
	return this;
}
int main()
{
	
	ttime tm1(9,10,36);
	ttime tm2(10,58,24);
	ttime tm3 = tm1 + tm2;
	ttime tm4 = tm2 - tm1;
    ttime tm5 = tm4 + 120;
    ttime tm6 = tm5 - 80;
	cout<<"tm3:   "<<tm3[0]<<"h:"<<tm3[1]<<"m:"<<tm3[2]<<"s"<<endl;
	cout<<"tm4:   "<<tm4[0]<<"h:"<<tm4[1]<<"m:"<<tm4[2]<<"s"<<endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值