C++ Time类重载运算符
生活随笔
收集整理的這篇文章主要介紹了
C++ Time类重载运算符
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述
設(shè)計(jì)一個(gè)時(shí)間類Time,要求:
1、包含時(shí)(hour),分(minute),秒(second)私有數(shù)據(jù)成員;
2、包含構(gòu)造函數(shù),重載關(guān)于一時(shí)間加上另一時(shí)間的加法運(yùn)算符"+"、重載輸出運(yùn)算符"<<"、重載輸入運(yùn)算符">>"。
要求,定義完Time類后,main函數(shù)中聲明對(duì)象time1,time2,time3,然后實(shí)現(xiàn)
輸入描述
輸入時(shí)間一、時(shí)間二,注意:在main函數(shù)中必須用cin>>time1>>time2實(shí)現(xiàn)輸入
輸出描述
輸出兩個(gè)時(shí)間相加的結(jié)果,注意,在main函數(shù)中必須用cout<<time3<<endl實(shí)現(xiàn)輸出
輸入樣例
12:30:59 2:30:01輸出樣例
15:01:00 #include<iostream>using namespace std;class Time{private:int hour; // 時(shí)(hour)int minute; // 分(minute)int second; // 秒(second)public:Time(int h, int m, int s){hour = h;minute = m;second = s;}int getHour(){return hour;}int getMinute(){return minute;}int getSecond(){return second;}friend Time operator + (Time &t1, Time &t2){ // 加法運(yùn)算符int h3, m3, s3;h3 = t1.getHour() + t2.getHour();m3 = t1.getMinute() + t2.getMinute();s3 = t1.getSecond() + t2.getSecond();if(s3 > 59){s3 = s3 % 60;m3 += 1;}if(m3 > 59){m3 = m3 % 60;h3 += 1;}if(h3 == 24){h3 = 0;}Time t3(h3, m3, s3);return t3;}friend istream &operator >>(istream &in, Time &t){ // 重載輸入運(yùn)算符char mh1, mh2;in >> t.hour >> mh1 >> t.minute >> mh2 >> t.second;return in;} friend ostream &operator<< (ostream &out,Time &t){ // 重載輸出運(yùn)算符if(t.hour < 10 && t.minute < 10 && t.second < 10){out << "0" << t.hour << ":" << "0" << t.minute << ":" << "0" << t.second;} else if(t.hour < 10 && t.minute < 10){out << "0" << t.hour << ":" << "0" << t.minute << ":" << t.second;} else if(t.hour < 10 && t.second < 10){out << "0" << t.hour << ":" << t.minute << ":" << "0" << t.second;} else if(t.minute < 10 && t.second < 10){out << t.hour << ":" << "0" << t.minute << ":" << "0" << t.second;} else if(t.hour < 10){out << "0" << t.hour << ":" << t.minute << ":" << t.second;} else if(t.minute < 10){out << t.hour << ":" << "0" << t.minute << ":" << t.second;} else if(t.second < 10){out << t.hour << ":" << t.minute << ":" << "0" << t.second;} else{out << t.hour << ":" << t.minute << ":" << t.second;}return out; } }; int main(){Time time1(0, 0, 0), time2(0, 0, 0),time3(0, 0, 0);cin >> time1 >> time2;time3 = time1 + time2; // 兩個(gè)時(shí)間相加cout << time3 << endl; // 輸出兩個(gè)時(shí)間相加的結(jié)果return 0; }總結(jié)
以上是生活随笔為你收集整理的C++ Time类重载运算符的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++ 复数类运算符重载
- 下一篇: C++ void类型指针的使用