C++程序设计:
设计一个时间类Time,要求如下:⑴:包含时(hour),分(minute),秒(second)私有数据成员。
⑵:包含构造函数,重载关于一段时间加上另一段时间的加法运算符“+”、重载关于一段时间减去另一段时间的减法运算符“-”、重载输入运算符“<<”和输出运算符“>>”
C++程序设计: 设计一个时间类Time,要求如下:
答案:2 悬赏:80
解决时间 2021-03-23 22:27
- 提问者网友:情系雨樱花
- 2021-03-23 12:47
最佳答案
- 二级知识专家网友:丢不掉的轻狂
- 2021-03-23 13:39
#include<iostream> #include<cstdlib> #include<string> using namespace std; class time { public: time() :h(0), m(0), s(0){} time(int newh, int newm, int news) :h(newh), m(newm), s(news){} int geth(){ return h; } int getm(){ return m; } int gets(){ return s; } void seth(int newh){ h = newh; } void setm(int newm){ m = newm; } void sets(int news){ s = news; } void display12(); private: int h, m, s; }; int main() { time t1(24, 4, 12), t2(2, 6, 6); t1.display12(); t2.display12(); system("pause"); return 0; } void time::display12() { string time; int h1; if (h > 12 && h != 24) { h1 = h - 12; time = "pm"; } else if (h == 24) { h1 = 0; time = "pm"; } else { h1 = h; time = "am"; } if (h1 / 10 == 0) cout << '0' << h1<<':'; else cout << h1<<':'; if (m / 10 == 0) cout << '0' << m << ':'; else cout << m << ':'; if (s / 10 == 0) cout << '0' << s; else cout << s; cout << time << endl; return; }
全部回答
- 1楼网友:野性且迷人
- 2021-03-23 13:59
#include<iostream>
using namespace std;
class Time
{
public:
Time(void);
Time(int hour,int minute,int second);
Time operator +(const Time &time);
Time operator -(const Time &time);
friend ostream& operator <<(ostream& out,const Time &time);
friend istream& operator >>(istream& in,const Time &time);
private:
int hour;
int minute;
int second;
};
Time::Time(void)
{
this->hour = 0;
this->minute = 0;
this->second = 0;
}
Time::Time(int hour,int minute,int second)
{
this->hour = hour;
this->minute = minute;
this->second = second;
}
Time Time::operator +(const Time &time)
{
Time newTime;
newTime.hour = this->hour + time.hour;
newTime.minute = this->minute+ time.minute;
newTime.second = this->second + time.second;
if(newTime.second >= 60)
{
newTime.second %= 60;
newTime.minute += 1;
}
if(newTime.minute >= 60)
{
newTime.minute %= 60;
newTime.hour += 1;
}
if(newTime.hour >= 24)
{
newTime.hour %= 24;
}
return newTime;
}
Time Time::operator -(const Time &time)
{
Time newTime;
newTime.hour = this->hour - time.hour;
newTime.minute = this->minute - time.minute;
newTime.second = this->second - time.second;
if(newTime.second < 0)
{
newTime.second += 60;
newTime.minute -= 1;
}
if(newTime.minute < 0)
{
newTime.minute += 60;
newTime.hour -= 1;
}
if(newTime.hour < 0)
{
newTime.hour += 24;
}
return newTime;
}
ostream& operator <<(ostream& out,const Time &time)
{
out<<time.hour<<":"<<time.minute<<":"<<time.second<<endl;
return out;
}
istream& operator >>(istream& in,const Time &time)
{
in>>time.hour>>time.minute>>time.second;
return in;
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯