定义一个时间类 Time,它能表示 24 小时制的时、分、秒,具体要求如下

张军 2779 0

(20 ) 定义一个时间类 Time,它能表示 24 小时制的时、分、秒,具体要求如下:


  1. (1) 供默认构造函数 Time(),将时、分、 秒都初始化成 0。

  2. (2) 提供构造函数 Time(int h, int m, int s)

  3. (3) 提供成员函数 set(int h, int m, int s),功能是调整时间。

  4. (4)能够分别获取时、分、秒信息。

  5. (5) 提供成员函数 display(),显示时间值。

  6. (6) 提供成员函数 equal(Time &other_time),比较是否与时间 other_time 相等。

  7. (7) 提供成员函数 increment()使时间增加一秒。

  8. (8) 提供成员函数 less_than(Time &other_time),比较是否早于时间 other_time。

// 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;
}



更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论