日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ Time类重载运算符

發布時間:2025/5/22 c/c++ 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ Time类重载运算符 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述

設計一個時間類Time,要求:
1、包含時(hour),分(minute),秒(second)私有數據成員;
2、包含構造函數,重載關于一時間加上另一時間的加法運算符"+"、重載輸出運算符"<<"、重載輸入運算符">>"。
要求,定義完Time類后,main函數中聲明對象time1,time2,time3,然后實現

cin>>time1>>time2; time3=time1+time2; cout<<time3<<endl;

輸入描述

輸入時間一、時間二,注意:在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类重载运算符的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。