检查并修改以下代码,使其运行正确。#include<iostream> using namespace std; class Time{ public: Time(int a,int b,int c){ hour=a; minute=b; second=c; } Time():hour(0),minute(0),second(0){ } Time Drop(Time&t){ Time q; q.hour=hour-t.hour; q.minute=minute-t.minute; q.second=second-t.second; if(q.second<0){ q.minute--; q.second+=60; } if(q.minute<0){ q.hour--; q.minute+=60; } } void disp(){ cout<<hour<<":"<<minute<<"'"<<second<<"""<<endl; } protected: int hour; int minute; int second; }; int main() { int h1,m1,s1,h2,m2,s2; cin>>h1>>m1>>s1>>h2>>m2>>s2; Time t1(h1,m1,s1), t2(h2,m2,s2), t; t=t1.Drop(t2); t.disp(); // t--; t=t.Drop(t); t.disp(); //(--t)--; t=t.Drop(t); t.disp(); //(t--).disp(); t.Drop(t).disp(); t.disp(); return 0; }
时间: 2023-08-06 20:10:03 浏览: 44
以下是代码的修改:
```c++
#include<iostream>
using namespace std;
class Time{
public:
Time(int a,int b,int c){
hour=a;
minute=b;
second=c;
}
Time():hour(0),minute(0),second(0){ }
Time Drop(Time&t){
Time q;
q.hour=hour-t.hour;
q.minute=minute-t.minute;
q.second=second-t.second;
if(q.second<0){
q.minute--;
q.second+=60;
}
if(q.minute<0){
q.hour--;
q.minute+=60;
}
return q; // 添加 return 语句
}
void disp(){
cout<<hour<<":"<<minute<<"'"<<second<<"''"<<endl; // 修改输出格式
}
// 重载运算符
Time operator--(){
second--;
if(second<0){
minute--;
second+=60;
}
if(minute<0){
hour--;
minute+=60;
}
return *this;
}
Time operator--(int){
Time temp=*this;
--(*this);
return temp;
}
protected:
int hour;
int minute;
int second;
};
int main() {
int h1,m1,s1,h2,m2,s2;
cin>>h1>>m1>>s1>>h2>>m2>>s2;
Time t1(h1,m1,s1), t2(h2,m2,s2), t;
t=t1.Drop(t2);
t.disp();
// t--
--t; // 先对 t 执行操作
t.disp();
// (--t)--
(--t)--; // 先对 t 执行操作,再对操作后的 t 执行操作
t.disp();
// (t--).disp()
(t--).disp(); // 先输出 t,再对 t 执行操作
t.disp();
// t.Drop(t).disp()
t.Drop(t).disp(); // 直接输出 t.Drop(t) 的结果
t.disp();
return 0;
}
```
主要修改如下:
1. 在 `Time Drop(Time&t)` 函数中添加了 `return` 语句,修复了编译错误。
2. 修改了 `disp()` 函数的输出格式。
3. 重载了 `--` 前置和后置运算符,使其能够对时间进行自减操作(注意修改后置运算符返回值)。
4. 在 `main()` 函数中使用了重载的运算符,以便进行时间的自减和输出操作。