C++ 面向对象编程实验题:类与对象 时间类

实验内容

1.定义时间类型myClock。要求有以下成员:
(1)要求自定义构造函数,实现时间的设置,初始值都为0;
(2)可以重新设置时间,并对数据的有效性进行检查。对于无效数据,则返回假的逻辑值;
(3)可以增加或减少时间(以秒为单位),考虑进位问题;
(4)显示时间:格式为“XX时XX分XX秒”(采用24小时制);
(5)闹钟。如果设置(或增加、减少后)的时间,如果是整点,则触发闹钟。

类的声明为:

class myClock
{
    
      
public: 
	myClock ();   
	bool SetTime(int NeoidwH, int NewM, int NewS);
	void IncreaseTime(int nsecond);
	void ReduceTime(int nsecond);
	void ShowTime();
	void Alarmclock();   // 闹钟,要考虑如果产生铃声?
private: 
    int Hour, Minute, Second;
};	
// 考虑进位(24小时制)

主函数:

#include <iostream>
#include "myClock.h"
using namespace std;

int main()
{
    
    	
	myClock c;
	c.ShowTime();  //显示时间
	c.SetTime(10,0,0);   //设置时间
	c.ShowTime();
	c.IncreaseTime(59);   //增加59秒时间
	c.ShowTime();
	c.ReduceTime(24*60*60);  //减少一天的时间
	c.ShowTime();
}

参考答案

myClock.cpp
#include "MyClock.h"
#include <Windows.h>

MyClock::MyClock()
{
    
    
}

MyClock::MyClock(int hour, int minute, int second) :Hour(hour), Minute(minute), Second(second)
{
    
    
}

bool MyClock::SetTime(int NeoidwH, int NewM, int NewS)
{
    
    
	if (NeoidwH >= 0 && NeoidwH <= 24)
	{
    
    
		if (NewM >= 0 && NewM < 60)
		{
    
    
			if (NewS >= 0 && NewS < 60)
			{
    
    
				this->Hour = NeoidwH == 24 ? 0 : NeoidwH;
				this->Minute = NewM;
				this->Second = NewS;
				this->Alarmclock();
				return true;
			}
		}
	}

	return false;
}

void MyClock::IncreaseTime(int nsecond)
{
    
    
	int h = nsecond / 3600;
	nsecond %= 3600;
	int m = nsecond / 60;
	nsecond %= 60;
	int s = nsecond;

	int resDay = h / 24;
	this->Hour += h % 24;
	this->Minute += m;
	this->Second += s;

	if (this->Second >= 60)
	{
    
    
		this->Second -= 60;
		this->Minute++;
	}

	if (this->Minute >= 60)
	{
    
    
		this->Minute -= 60;
		this->Hour++;
	}

	if (this->Hour >= 24)
	{
    
    
		this->Hour -= 24;
	}

	this->Alarmclock();
}

void MyClock::ReduceTime(int nsecond)
{
    
    
	int h = nsecond / 3600;
	nsecond %= 3600;
	int m = nsecond / 60;
	nsecond %= 60;
	int s = nsecond;

	this->Hour -= h % 24;
	this->Minute -= m;
	this->Second -= s;

	if (this->Second < 0)
	{
    
    
		this->Second += 60;
		this->Minute--;
	}

	if (this->Minute < 0)
	{
    
    
		this->Minute += 60;
		this->Hour--;
	}

	if (this->Hour < 0)
	{
    
    
		this->Hour += 24;
	}

	this->Alarmclock();
}

void MyClock::ShowTime()
{
    
    
	cout << this->Hour << " 时 " << this->Minute << " 分 " << this->Second << " 秒 " << endl;
}

void MyClock::Alarmclock()
{
    
    
	if (this->Minute == 0 && this->Second == 0)
	{
    
    
		cout << "*整点响铃*" << endl;
		Beep(784, 1200);  
		Beep(1046, 1000);  
		Beep(988, 300);
		Beep(1175, 400);
		Beep(1046, 400);
		Beep(784, 400);
		Beep(659, 400);
		Beep(880, 1000);
		// 猜猜这是什么音乐?
	}
}

猜你喜欢

转载自blog.csdn.net/Ouchdex/article/details/116277492