c++

本文介绍了C++中定义的complex类,用于表示带有时、分、秒的时间,并展示了加减法运算和数组访问功能的应用。
摘要由CSDN通过智能技术生成

#include <iostream>
using namespace std;
class complex
{
	public:
		complex(int h,int m,int s) {this->h = h;this->m = m;this->s = s;}
		complex() {h=0;m=0;s=0;}
 
		complex operator+ (complex &t)
		{
			complex ti;
			ti.s = this->s + t.s;
			ti.m = this->m + t.m;
			ti.h = this->h + t.h;
			if(ti.s > 59) {ti.m+=1;ti.s-=60;}
			if(ti.m > 59) {ti.h+=1;ti.m-=60;}
			if(ti.h > 23) {ti.h-=24;}
			return ti;
		}
 
 
		complex operator- (complex &t)
		{
			complex ti;
			if(this->s < t.s) {this->s+=60;this->m-=1;}
			ti.s = this->s - t.s;
			if(this->m < t.m) {this->m+=60;this->h-=1;}
			ti.m = this->m - t.m;
			if(this->h < t.h) {this->h+=24;}
			ti.h = this->h - t.h;
			return ti;
		}
 
		complex operator+ (int t)
		{
			complex ti;
			ti.s = this->s + t;
			ti.m = this->m;
			ti.h = this->h;
			while(ti.s > 59) {ti.m+=1;ti.s-=60;}
			while(ti.m > 59) {ti.h+=1;ti.m-=60;}
			while(ti.h > 23) {ti.h-=24;}
			return ti;
		}
 
		complex operator- (int t)
		{
			complex ti;
			while(this->s < t) {this->s+=60;this->m-=1;}
			ti.s = this->s - t;
			while(this->m < 0) {this->m+=60;this->h-=1;}
			ti.m = this->m;
			while(this->h < 0) {this->h+=24;}
			ti.h = this->h;
			return ti;
		}
 
		int &operator[] (int i)
		{
			switch(i)
			{
			case 0:
				return s;
			case 1:
				return m;
			case 2:
				return h;
			default:
				cout<<"错误输入"<<endl;
			}
		}
 
 
		void show() {cout<<h<<"时"<<m<<"分"<<s<<"秒"<<endl;}
private:
	int s;
	int m;
	int h;
};
 
int main(int argc, const char *argv[])
{
	complex t0(5,23,4);
	complex t1(6,55,5);
	complex t2;
	
	t2=t0-t1;
	t2.show();
	t2=t0+t1;
	t2.show();
	t2=t1+11379459;
	t2.show();
	t2=t0-124985739;
	t2.show();
	cout<<t2[1]<<"分"<<t2[0]<<"秒"<<t2[2]<<"时"<<endl;
 
	t2[1]=55;
	cout<<"t2[1]="<<t2[1]<<endl;
	return 0;
}
 

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值