您的位置:首页 > 其它

Time类中的运算符重载(3)-前置++,后置++

2016-05-21 13:32 351 查看
问题描述及代码:

/*
*copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:hellow.cpp
*作者:田甜
*完成日期:2016年5月21日
*版本号:v1.0
*
*问题描述:
*输入描述:实现Time类中的运算符重载。
*程序输出:////
*/
#include <iostream>

using namespace std;
class CTime
{
private:
int hour,minute,second;
public:
CTime(int h,int m,int s):hour(h),minute(m),second(s){};
CTime& operator++();
CTime& operator--();
CTime operator++(int);
CTime operator--(int);
CTime operator+(CTime &c);
CTime operator-(CTime &c);
CTime operator+(int s);
CTime operator-(int s);
friend ostream& operator<<(ostream& output,CTime t);
friend istream& operator>>(istream& input,CTime &t);
};
ostream& operator<<(ostream& output,CTime t)
{
output<<t.hour<<":"<<t.minute<<":"<<t.second<<endl;
return output;
}

istream& operator>>(istream& input,CTime &t)
{
char c1,c2;
cout<<""<<endl;
while(1)
{
input>>t.hour>>c1>>t.minute>>c2>>t.second;
if((c1==':'&&c2==':')&&(t.hour>-1&&t.hour<23&&t.minute>-1&&t.minute<59&&t.second>-1&&t.second<59))break;
cerr<<"信息有误或格式不正确。"<<endl;

}
return input;
}

CTime& CTime::operator++()
{
*this=*this+1;
return *this;
}

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

CTime CTime::operator++(int)
{
CTime t=*this;
*this=*this+1;
return t;
}

CTime CTime::operator--(int)
{
CTime t=*this;
*this=*this-1;
return t;
}

CTime CTime::operator + (CTime &t)
{

int h,m,s;
s=second+t.second;
m=minute+t.minute;
h=hour+t.hour;
if (s>59)
{
s-=60;
m++;
}
if (m>59)
{
m-=60;
h++;
}
while (h>23) h-=24;
CTime t0(h,m,s);
return t0;
}

CTime CTime::operator-(CTime &t)
{
int h,m,s;
s=second-t.second;
m=minute-t.minute;
h=hour-t.hour;
if (s<0)
{
s+=60;
m--;
}
if (m<0)
{
m+=60;
h--;
}
while (h<0) h+=24;
CTime t0(h,m,s);
return t0;
}

CTime CTime::operator-(int t)
{
int ss=t%60;
int mm=(t/60)%60;
int hh=t/3600;
CTime t0(hh,mm,ss);
return *this-t0;
}

CTime CTime::operator+(int t)
{
int ss=t%60;
int mm=(t/60)%60;
int hh=t/3600;
CTime t0(hh,mm,ss);
return *this+t0;
}
int main()
{
CTime t1(10,11,12),t2(12,13,14);
t1++;
t2--;
cout<<t1<<t2<<endl;
++t2;
++t1;
cout<<t1<<t2<<endl;
cin>>t1>>t2;
cout<<t1<<t2<<endl;
return 0;
}


运行结果:



心得体会:

友元函数要改变对象的私有成员的值,必须在形参里有该类对象的引用。

前置++效率较高,且返回类型是引用,后置++返回类型是该类的一个对象。

另外在使用重载>>设置时间时,我意外地输入了“5 6 7(换行)2 3 4”,结果再提示一次错误后成为死循环不停地输出“信息或格式有误”,目前不知道原因,如果有大牛知道的话欢迎留言告诉我,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: