C++ Time类重载运算符
生活随笔
收集整理的這篇文章主要介紹了
C++ Time类重载运算符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
設計一個時間類Time,要求:
1、包含時(hour),分(minute),秒(second)私有數據成員;
2、包含構造函數,重載關于一時間加上另一時間的加法運算符"+"、重載輸出運算符"<<"、重載輸入運算符">>"。
要求,定義完Time類后,main函數中聲明對象time1,time2,time3,然后實現
輸入描述
輸入時間一、時間二,注意:在main函數中必須用cin>>time1>>time2實現輸入
輸出描述
輸出兩個時間相加的結果,注意,在main函數中必須用cout<<time3<<endl實現輸出
輸入樣例
12:30:59 2:30:01輸出樣例
15:01:00 #include<iostream>using namespace std;class Time{private:int hour; // 時(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){ // 加法運算符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){ // 重載輸入運算符char mh1, mh2;in >> t.hour >> mh1 >> t.minute >> mh2 >> t.second;return in;} friend ostream &operator<< (ostream &out,Time &t){ // 重載輸出運算符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; // 兩個時間相加cout << time3 << endl; // 輸出兩個時間相加的結果return 0; }總結
以上是生活随笔為你收集整理的C++ Time类重载运算符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 复数类运算符重载
- 下一篇: C++ void类型指针的使用