早教吧 育儿知识 作业答案 考试题库 百科 知识分享

编写Date类,其中包含年月日,使用运算符重载,使之支持前置++和后置++。

题目详情
编写Date类,其中包含年月日,使用运算符重载,使之支持前置++和后置++。
▼优质解答
答案和解析
我写了一个时间类的加减运算符重载,看看吧,希望对你有帮助。
#include
using namespace std;
class Time{
private:
int hour;
int minute;
int second;
public:
Time()
{}
Time(int m_hour,int m_minute,int m_second){
hour=m_hour;
minute=m_minute;
second=m_second;
}
//构造函数 的重载
void Time1(int m_hour,int m_minute,int m_second){
hour=m_hour;
minute=m_minute;
second=m_second;
}
Time operator+(const Time &t1) const;
Time operator-(const Time &t1) const;
void ShowTime();
};
//加法的重载
Time Time::operator +(const Time &t1) const{
Time t4;
t4.second=second+t1.second;
t4.minute=minute+t1.minute;
t4.hour=hour+t1.hour;
if(t4.second>59){
t4.second=t4.second-60;
t4.minute=t4.minute+1;
}
if(t4.minute>59){
t4.minute=t4.minute-60;
t4.hour=t4.hour+1;
}

if(t4.hour>23){
t4.hour=t4.hour-23;
}

return t4;
}
//减法的重载
Time Time::operator -(const Time &t1) const{
Time t4;
t4.second=second-t1.second;
t4.minute=minute-t1.minute;
t4.hour=hour-t1.hour;
if(t4.second<0){
t4.second=t4.second+60;
t4.minute=t4.minute-1;
}
if(t4.minute<0){
t4.minute=t4.minute+60;
t4.hour=t4.hour-1;
}

if(t4.hour<0){
t4.hour=t4.hour+23;
}

return t4;
}
void Time::ShowTime(){
cout<}

void main()
{
Time t1,t2,t3;
int h1,m1,s1;
int h2,m2,s2;
bool operation;
bool ifexit=false;
while(!ifexit){
cout< cin>>h1;
cout< cin>>m1;
cout< cin>>s1;
t1.Time1(h1,m1,s1);
cout< t1.ShowTime();
cout< cin>>h2;
cout< cin>>m2;
cout< cin>>s2;
t2.Time1(h2,m2,s2);
cout< t2.ShowTime();
cout< cout< cout< cout< cout< cin>>operation;
if (operation){
t3=t1+t2;
cout< t3.ShowTime();
}
else{
t3=t1-t2;
cout< t3.ShowTime();
}
cout< cout< cout< cout< cout< cin>>ifexit;
}
}
看了编写Date类,其中包含年月日...的网友还看了以下: