东莞网站设计与网站制作/官网首页入口百度
Link
c++课作业,写了几万行代码还是第一次写 class
,重载 +=/-=/++/--
和 cin/cout
什么的还是第一次。
话说提交作业这个平台居然还支持万能头文件,还是要点个赞的。
主要就是注意 friend
和 const
吧,
+=/-=
不能像<,-,+..
一样加const
,或许是因为值修改了?重载cin/cout
的函数声明需要加friend
并把函数体写到类的外面,其实感觉类里只写声明然后把所有函数体都写到外面蛮舒服的。重载cin
不能加const
,重载cout
最好加上const
,好像是因为什么const
为常饮用,既可以引用左值也可以引用右值,总之能加const就加就对了++,--
还分前自增后自增,没搞懂那函数是啥意思,懒。反正照着网上抄就对了。
题目
Input
21 10 35
10 15 25
Output
07:26:00
21:10:34
10:15:27
07:26:01
21:10:32
10:15:29
Code
#include <bits/stdc++.h>
using namespace std;
class Time {
private:int h, m, s; //小时分钟秒
public:Time operator ++();//前置型Time operator ++(int);//后置型Time operator --();//前置型Time operator --(int);//后置型friend istream & operator >> (istream &in,Time &a);friend ostream & operator << (ostream &out,const Time &a);Time& operator += (const Time &b) {s += b.s;m += b.m;h += b.h;if(s > 59) {s -= 60;m++;}if(m > 59) {m -= 60;h++;}if(h > 23)h -= 24;return *this;}Time& operator -= (const Time &b) {s -= b.s;m -= b.m;h -= b.h;if(s < 0) {s += 60;m--;}if(m < 0) {m += 60;h--;}if(h < 0)h += 24;return *this;}Time Dec() { //--s--;if(s < 0) {s += 60;m--;}if(m < 0) {m += 60;h--;}if(h < 0)h += 24;return (*this);}Time Inc() { //--s++;if(s > 59) {s -= 60;m++;}if(m > 59) {m -= 60;h++;}if(h > 23)h -= 24;return (*this);}
}t;
Time Time::operator ++ (){ //前置++return Inc();
}
Time Time::operator ++ (int){ //后置++Time p = *this;Inc();return p;
}
Time Time::operator -- (){ //前置--return Dec();
}
Time Time::operator -- (int){ //后置--Time p = *this;Dec();return p;
}
istream & operator >> (istream &in,Time &a) {in >> a.h >> a.m >> a.s;return in;
}
ostream & operator << (ostream &out,const Time &a) {if(a.h < 10) out << '0';out << a.h << ':';if(a.m < 10) out << '0';out << a.m << ':';if(a.s < 10) out << '0';out << a.s;return out;
}
void solve() {Time t1, t2;cin >> t1 >> t2;cout << (t1 += (t2++)) << endl;cout << (t1 -= t2) << endl;cout << ++t2 << endl;cout << (t2 += (t1--)) << endl;cout << --t1 << endl;cout << (t2 -= t1) << endl;
}
signed main() {ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
// int T; scanf("%d", &T); while(T--)
// int T; cin >> T; while(T--)solve();return 0;
}