(20 分) 定义一个时间类 Time,它能表示 24 小时制的时、分、秒,具体要求如下:
(1) 提供默认构造函数 Time(),将时、分、 秒都初始化成 0。
(2) 提供构造函数 Time(int h, int m, int s)。
(3) 提供成员函数 set(int h, int m, int s),功能是调整时间。
(4)能够分别获取时、分、秒信息。
(5) 提供成员函数 display(),显示时间值。
(6) 提供成员函数 equal(Time &other_time),比较是否与时间 other_time 相等。
(7) 提供成员函数 increment(),使时间增加一秒。
(8) 提供成员函数 less_than(Time &other_time),比较是否早于时间 other_time。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | // ConsoleApplication1.cpp : 定义控制台应用程序的入口点。 //《面向对象程序设计(C++)》期末考试试题(综合大作业)(原创张军(QQ:360901061)) #include "stdafx.h" #include <iostream>; using namespace std; class Time { public : // (1) 提供默认构造函数 Time(),将时、分、 秒都初始化成 0。 Time() { _h = 0; _m = 0; _s = 0; } // (2) 提供构造函数 Time(int h, int m, int s)。 Time( int h, int m, int s) { check(h, m, s); _h = h; _m = m; _s = s; } bool check( int h, int m, int s){ //判断输入值合法性 if (h<0 || h>23 || m < 0 || m >59 || s<0 || s > 59){ throw string( "时间格式不合法" ); } } //(3) 提供成员函数 set(int h, int m, int s),功能是调整时间。 void set( int h, int m, int s){ check(h, m, s); _h = h; _m = m; _s = s; } //(4)能够分别获取时信息。 int getH(){ return _h; } //(4)能够分别获取分信息。 int getM(){ return _m; } //(4)能够分别获取秒信息。 int getS(){ return _s; } //(5) 提供成员函数 display(),显示时间值。 void display(){ cout << _h << " 时 " << _m << " 分 " << _s << " 秒 " << endl; } //(6) 提供成员函数 equal(Time &other_time),比较是否与时间 other_time 相等。 bool equal(Time other_time){ if (_h == other_time._h && _m == other_time._m && _s == other_time._s){ return true ; } else { return false ; } } //(7) 提供成员函数 increment(),使时间增加一秒。 void increment(){ _s++; if (_s == 60) { _m++; _s = 0; if (_m == 60) { _h++; _m = 0; if (_h == 24) { _h = 0; _m = 0; _s = 0; } } } } //(8) 提供成员函数 less_than(Time &other_time),比较是否早于时间 other_time。 bool less_than(Time other_time){ if (_h < other_time._h) { return true ; } else if (_h == other_time._h && _m < other_time._m) { return true ; } else if (_h == other_time._h && _m == other_time._m && _s < other_time._s) { return true ; } else { return false ; } } //表示 24 小时制的时、分、秒 private : int _h; int _m; int _s; }; int main() { //Time t; Time t(22, 59, 59); //Time t2(10, 11, 12); //t.increment(); //t.set(15, 16, 17); t.display(); //cout << t.getH() << endl; //cout << t.equal(t2) << endl; //cout << t2.less_than(t) << endl; system ( "pause" ); return 0; } |
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com