【c++运算符重载】时间类(24小时)可实现秒数前缀--和后缀--

#include<iostream>
using namespace std;
class time24
{
public:
	time24(int h = 0, int m = 0, int s = 0) :hours(h), minutes(m), seconds(s){}
	void set(int h, int m, int s);
	void get(int &h, int &m, int &s);
	time24 operator-(const int &s);
	time24 operator--();//--i
	time24 operator--(int);//i--
	bool operator==(time24& t);
private:
	int hours;
	int minutes;
	int seconds;
};

void time24::set(int h, int m, int s)
{
	hours = h;
	minutes = m;
	seconds = s;
}

void time24::get(int &h, int &m, int &s)
{
	h = hours;
	m = minutes;
	s = seconds;
}

time24 time24::operator-(const int &s)
{
	time24 result;
	int base = this->hours * 60 * 60 + this->minutes * 60 + this->seconds;
	base = base + (60 * 60 * 24 - s /*% (60 * 60 * 24)*/);

	//加个判断
	result.seconds = base;
	result.minutes = base / 60;
	result.hours = base / 60 / 60;
	result.seconds %= 60;
	result.minutes %= 60;
	result.hours %= 24;
	return result;
}

time24 time24::operator--()
{
	*this = *this - 1;
	return *this;
}

time24 time24::operator--(int)
{
	time24 temp;
	temp = *this;
	*this = *this - 1;
	return temp;
}

bool time24::operator==(time24& t)
{
	if (hours == t.hours && minutes == t.minutes && seconds == t.seconds)
		return true;
	else
		return false;
}

int main()
{
	int h, m, s;
	time24 t1;
	cin >> h >> m >> s;
	t1.set(h, m, s);
	time24 t2;

	t2 = --t1;

	if (t1 == t2)
		cout << "t1==t2" << endl;
	else
		cout << "t1!=t2" << endl;

	t2.get(h, m, s);

	cout << h << ':' << m << ':' << s << endl;

	t2 = t1--;

	if (t1 == t2)

		cout << "t1==t2" << endl;
	else
		cout << "t1!=t2" << endl;

	t2.get(h, m, s);

	cout << h << ':' << m << ':' << s << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值