C++编程编写一个时间类time,包含时,分,秒数据成员实现时间的加,减,输入和输出,其中时
1个回答
展开全部
#include <iostream>
using namespace std;
class time
{
int hour;
int min;
int sec;
public:
time(int h=0,int m=0,int s=0)
{
hour=h;min=m;sec=s;
}
~time(){}
friend time operator+(time t1,time t2);
friend time operator-(time t1,time t2);
void operator=(time);
friend ostream& operator<<(ostream &,time);
friend istream& operator>>(istream &,time);
};
int main()
{
time t1,t2(100,300,500),t3(1,2,3);
cout<<t1<<endl;
cout<<t2<<endl;
cout<<t3<<endl;
cout<<t2-t3<<endl;
cout<<t2+t3<<endl;
t3=t2;
cout<<t3<<endl;
}
time operator+(time t1,time t2)
{
time t3;
t3.hour=t1.hour+t2.hour;
t3.min=t1.min+t2.min;
t3.sec=t1.sec+t2.sec;
while(t3.sec>=60)
{
t3.sec-=60;
t3.min++;
}
while(t3.min>=60)
{
t3.min-=60;
t3.hour++;
}
return t3;
}
time operator-(time t1,time t2)
{
time t3;
t3.hour=t1.hour-t2.hour;
t3.min=t1.min-t2.min;
t3.sec=t1.sec-t2.sec;
while(t3.sec<0)
{
t3.sec+=60;
t3.min--;
}
while(t3.min<0)
{
t3.min+=60;
t3.hour--;
}
return t3;
}
void time::operator=(time t)
{
hour=t.hour;
min=t.min;
sec=t.sec;
}
ostream& operator<<(ostream &os,time t)
{
while(t.sec>=60)
{
t.sec-=60;
t.min++;
}
while(t.min>=60)
{
t.min-=60;
t.hour++;
}
os<<t.hour<<" :"<<t.min<<":"<<t.sec<<endl;
return os;
}
istream& operator>>(istream &is,time t)
{
is>>t.hour>>t.min>>t.sec;
return is;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询