C++第四天

本文介绍了一个C++编程中的自定义时间类times,包含了时间对象的构造、显示、加法和减法运算,以及对时间分秒的直接访问。
摘要由CSDN通过智能技术生成

#include <iostream>

using namespace std;

class times
{
public:
	times()
	{
		h = -1;
		m = -1;
		s = -1;
	}
	times(int h, int m, int s)
	{
		this->h = h;
		this->m = m;
		this->s = s;
	}
	void show()
	{
		cout << h << ":" << m << ":" << s << endl;
	}
	times operator+(times T) //+
	{
		times res;
		res.h = T.h + h;
		res.m = T.m + m;
		res.s = T.s + s;
		//	cout<<T.s<<" "<<s<<" "<<res.s<<endl;
		if (res.s > 60)
		{
			res.s = res.s % 60;
			res.m = res.m + 1;
		}
		if (res.m > 60)
		{
			res.m = res.m % 60;
			res.h = res.h + 1;
		}
		return res;
	}
	times operator-(times T) //-
	{
		times res;
		res.h = h - T.h;
		res.m = m - T.m;
		res.s = s - T.s;
		// cout<<T.s<<" "<<s<<" "<<res.s<<endl;
		if (res.s < 0)
		{
			res.s = (res.s + 60) % 60;
			res.m = res.m - 1;
		}
		if (res.m < 0)
		{
			res.m = (res.m + 60) % 60;
			res.h = res.h - 1;
		}
		if (res.h < 0)
		{
			res.h = 0;
		}
		return res;
	}
	times operator+(int n) //+
	{
		this->s = s + n;
		if (this->s > 60)
		{
			this->s = this->s % 60;
			this->m = this->m + 1;
		}
		if (this->m > 60)
		{
			this->m = this->m % 60;
			this->h = this->h + 1;
		}
		return *this;
	}
	times operator-(int n) //-
	{
		this->s = s - n;
		if (this->s < 0)
		{
			this->s = (this->s + 60) % 60;
			this->m = this->m - 1;
		}
		if (this->m < 0)
		{
			this->m = (this->m + 60) % 60;
			this->h = this->h - 1;
		}
		if (this->h < 0)
		{
			this->h = 0;
		}
		return *this;
	}

	int &operator[](int i)
	{
		if (i == 0)
		{
			return this->s;
		}
		else if (i == 1)
		{
			return this->m;
		}
		else if (i == 2)
		{
			return this->h;
		}
	}

	int h;
	int m;
	int s;
};

int main(int argc, const char *argv[])
{
	times T0(15, 34, 30);
	T0.show();

	int sec = T0[0];
	cout << sec << endl;

	T0[0] = 55;
	cout << T0[0] << endl;

	times T1(14, 01, 59);
	times T3;
	//	T3=T0+T1;
	//	T3.show();

	T3 = T0 - T1;
	T3.show();

	T3 = T3 + 10;
	T3.show();

	T3 = T3 - 10;
	T3.show();
	return 0;
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值