重载“++”,“--”
描述
生成时间类Time。类包含私有数据成员h、m、s,分别表示当前时刻的小时、分钟和秒。提供成员函数display(),显示当前时刻,重载“++”,“--”为Time类的成员函数,分别表示将当前时刻推后和提前一个小时。时间的表示采用24小时制。
输入时分秒,显示当前时刻,推后一个小时的时刻,及提前一个小时的时刻。
输入
时、分、秒。
输出
time:当前时间
++time:推后一个小时的时间
--time:提前一个小时的时间
输入输出示例
输入 | 输出 | |
示例 1 | | |
1、
#include<iostream>
using namespace std;
class Time
{
private:
int hour, minute, second;
public:
Time() :hour(0), minute(0), second(0) {};
Time(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
Time operator ++(int a);
Time operator --(int b);
void display()
{
cout << hour << ":" << minute << ":" << second << endl;
}
};
Time Time::operator ++(int a)
{
++hour;
if (hour >= 24)
{
hour = hour - 24;
}
return *this;
}
Time Time::operator --(int b)
{
--b;
if (b >= 24)
{
hour = hour - 24;
}
if (b < 1)
{
b = 24 + b;
}
hour = b;
return *this;
}
int main()
{
int h, m, s;
cin >> h >> m >> s;
Time a(h, m, s);
cout<<"time:";
a.display();
a.operator++(0);
cout<<"++time:";
a.display();
a.operator--(h);
cout<<"--time:";
a.display();
return 0;
}
2、
#include<iostream>
using namespace std;
class Time {
int hour, minute, seconds;
public:
Time(int h, int m, int s) :hour(h), minute(m), seconds(s) {}
void display1() {
cout << "time:" << hour << ":" << minute << ":" << seconds << endl;
}
void display2() {
if(hour==24)
cout << "++time:0:" << minute << ":" << seconds << endl;
else
cout << "++time:" << hour << ":" << minute << ":" << seconds << endl;
}
void display3() {
if(hour==-1)
cout << "--time:23:"<< minute << ":" << seconds << endl;
else
cout << "--time:" << hour << ":" << minute << ":" << seconds << endl;
}
Time operator++() {
++hour;
return *this;
}
Time operator--() {
--hour;
return *this;
}
};
int main() {
int h, m, s;
cin >> h >> m >> s;
Time A(h, m, s),B(h,m,s);
A.display1();
// A.operator++();
++A;
A.display2();
B.operator--();
B.display3();
return 0;
}
3、
#include<iostream>
using namespace std;
class Time {
private:
int h;
int m;
int s;
public:
void set() {
cin >> h >> m >> s;
}
void display() {
cout << "time:"<< h << ':' << m << ':' << s << endl;
}
Time operator++() {
h++;
if (h == 24) h = 0;
cout << "++time:" << h << ':' << m << ':' << s << endl;
return *this;
}
Time operator--() {
if (h < 2) h += 24;
h = h - 2;
cout << "--time:" << h << ':' << m << ':' << s << endl;
return *this;
}
};
int main()
{
Time t;
t.set();
t.display();
t.operator++();
t.operator--();
return 0;
}