新手如何用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;
}