本文为博主原创文章,未经博主允许不得转载。
版权为陈博超所有,第一次于2020年11月22日发表于BLOG上
本BLOG上原创文章未经本人许可,不得用于商业用途。转载请经允许后注明出处,否则保留追究法律责任的权利。
编写一个时间类,实现时间的加减运算并输出
要求:该时间类可以自加自减,同时可以对两个时间相加相减(即重载运算符++、–、+、-)
码字不宜,穷酸学生,各位老板打赏个1分钱支持一下,谢谢各位老板。
#include<iostream>
#include<windows.h>
using namespace std;
class Time {
public:
int minute;
int sec;
Time() { //默认构造函数
minute = 0;
sec = 0;
}
Time(int m, int s):minute(m), sec(s)//构造函数重载
{}
Time& operator++(); //声明运算符“++”重载为成员函数
Time& operator--(); //声明运算符“--”重载为成员函数
friend Time& operator+=(Time& a, Time& b);
//声明运算符“+=”重载为友元函数
friend Time& operator-=(Time& a, Time& b);
//声明运算符“-=”重载为友元函数
void Print();
};
Time& Time::operator++() { //重载“++”运算符
sec++;
if (sec >= 60) {
sec -= 60;
minute++;
}
return *this;
}
Time& Time::operator--() { //重载“--”运算符
sec--;
if (sec < 0) {
sec += 60;
minute--;
}
return *this;
}
Time& operator+=(Time& a, Time& b) { //重载“+=”运算符
int minute;
int sec;
if (a.sec + b.sec >= 60) {
a.sec += b.sec;
a.sec -= 60;
a.minute++;
}
else {
a.sec += b.sec;
}
if (a.minute + b.minute >= 60) {
a.minute += b.minute;
a.minute -= 60;
}
else {
a.minute += b.minute;
}
return a;
}
Time& operator-=(Time& a, Time& b) { //重载“-=”运算符
int minute;
int sec;
int t1, t2, t;
t1 = a.minute * 60 + a.sec;
t2 = b.minute * 60 + b.sec;
if (t1 >= t2) {
t = t1 - t2;
}
else {
t = t2 - t1;
}
a.minute = t / 60;
a.sec = t % 60;
return a;
}
void Time::Print() { //显示成员函数
cout << "当前时间是:";
cout << minute << "分" << sec << "秒" << endl;
}
int main() {
Time time1, time2, time3;
int a;
cout << "请输入分钟:" << endl;
cin >> time1.minute;
cout << "请输入秒钟:" << endl;
cin >> time1.sec;
cout << "当前时间是:" << time1.minute << "分:" << time1.sec << "秒" << endl;
cout << "--------------------------------" << endl;
cout << "请输入操作" << endl << "1.整数计时" << endl << "2.倒数计时" << endl << "3.时间相加" << endl << "4.时间相减" << endl;
cout << "--------------------------------" << endl;
while (scanf("%d", &a) != EOF) {
switch (a) {
case 1:
for (int i = 0; i < 8; i++) {
++time1;
Sleep(1000);
time1.Print();
}
break;
case 2:
for (int i = 0; i < 8; i++) {
--time1;
Sleep(1000);
time1.Print();
}
break;
case 3:
cout << "请输入需要相加的时间(分钟)" << endl;
cin >> time2.minute;
cout << "请输入需要相加的时间(秒钟)" << endl;
cin >> time2.sec;
time1 += time2;
time1.Print();
break;
case 4:
cout << "请输入需要相减的时间(分钟)" << endl;
cin >> time3.minute;
cout << "请输入需要相减的时间(秒钟)" << endl;
cin >> time3.sec;
time1 -= time3;
time1.Print();
break;
}
}
return 0;
}
码字不宜,穷酸学生,各位老板打赏个1分钱支持一下,谢谢各位老板。