新手如何用C++写一个时间类

新手如何用C++写一个时间类

编程环境是VS2019
过程很简单只要把每一个成员函数都定义好就🆗了
代码如下

#include<iostream>
using namespace std;
class Time          //定义一个时间类
{
private :
 int hour, minute, second;
public:
 Time(int a=0 ,int b=0,int c=0);
 void settime();
 void show();
 void add();
 void reduce();
};
Time::Time(int a,int b,int c)
{
 if (a < 0 || a>24 || b < 0 || b>59 || c < 0 || c>59)
 {
  cout << "wrong time" << endl;
 }
 else
 {
  hour = a; minute = b;second = c;
 }
}
void Time::settime()
{
 int a, b, c;
 cout << "输入时/分/秒" << endl;
 cin >> a >> b >> c;
 if (a < 0 || a>24 || b < 0 || b>59 || c < 0 || c>59)
 {
  cout << "wrong time" << endl;
 }
 else
 {
  hour = a; minute = b;second = c;
  cout << "进行下一项" << endl;
 }
}
void Time::show()
{
 cout << "Hour---     " << hour << "     Minute---     " << minute << "     Second---     " << second << endl;
 cout << "进行下一项" << endl;
}
void Time::add()
{
 int n,x=0;
 cout << "请输入要增加的秒数:"<<endl;
 cin >> n;
 x = 3600 * hour + 60 * minute + second+n;
 hour = x / 3600;
 minute = (x % 3600) / 60;
 second = x % 60;
 cout << "done" << endl;
 cout << "进行下一项" << endl;
}
void Time::reduce()
{
 int n, x=0;
 cout << "请输入要减少的秒数:" << endl;
 cin >> n;
 x = 3600 * hour + 60 * minute + second - n;   //先换算成秒,再进行运算
 hour = x / 3600;
 minute = (x % 3600) / 60;
 second = x % 60;
 cout << "done" << endl;
 cout << "进行下一项" << endl;
}
int main()                //主函数
{
 Time time;
 cout << "功能:" << endl;
 cout << "-------设定时间-------1" << endl;
 cout << "-------增加秒数-------2" << endl;
 cout << "-------减少秒数-------3" << endl;
 cout << "-------显示时间-------4" << endl;
 cout << "-------结束程序-------0" << endl;
 int m;        //用do while 循环来保证程序能够一直运行
 do {
  cin >> m;
  switch (m)
  {
  case 1:
  {time.settime();
  break;}
  case 2:
  {time.add();
  break;}
  case 3:
  {time.reduce();
  break;}
  case 4:
  {time.show();
  break;}
  case 0:
  {
   cout << "程序结束" << endl;
   return 0;}
  default:
  {cout << "wrong num" << endl;}
  }
 } while (m);
 return 0;
}
  • 2
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值