设计一简单C++时间类,包含时分秒3个数据成员项,以秒为单位增加时间的成员函数,以及时间的显示输出函数

设计一简单C++时间类,包含时分秒3个数据成员项,以秒为单位增加时间的成员函数,以及时间的显示输出函数,第1张

//MyTime.h 文件中的代码:

#ifndef _MY_TIME_H_

#define _MY_TIME_H_

class MyTime

{

public:

MyTime(void)//默认构造函数

MyTime(short hour, short minute, short second)

~MyTime(void)

private:

short m_Hour

short m_Minute

short m_Second

public:

void AddSecond()

void PrintTime()

}

#endif //MyTime.cpp 文件中代码:

#include <iostream>

#include "MyTime.h"

MyTime::MyTime(void)

:m_Hour(0), m_Minute(0), m_Second(0)

{

}

MyTime::MyTime(short hour, short minute, short second)

:m_Hour(hour), m_Minute(minute), m_Second(second)

{

}

MyTime::~MyTime(void)

{

}

void MyTime::AddSecond()

{

++m_Second

if (m_Second >= 60)

{//如果秒数达到60,则分数进位,同时秒数清为0

m_Second = 0

++m_Minute

if (m_Minute >= 60)

{//如果分数达到60,则时数进位,同时分数清为0

m_Minute = 0

++m_Hour

if (m_Hour >= 24)

{//如果时数达到24,说明已为0点,时数清为0

m_Hour = 0

}

}

}

}

//打印时间

void MyTime::PrintTime()

{

std::cout<<m_Hour<<":"<<m_Minute<<":"<<m_Second<<std::endl

} //Main.cpp 文件中的测试代码:

#include "MyTime.h"

int main()

{

MyTime time

time.PrintTime()

time.AddSecond()

time.PrintTime()

MyTime time2(23, 59, 59)

time2.PrintTime()

time2.AddSecond()

time2.PrintTime()

return 0

}

#include<iostream.h>

classTimer

{

longsecond

public:

Timer(intsecond)

{

this->second=second

}

Timer(intminute,intsecond)

{

this->second=minute*60+second

}

Timer(inthour,intminute,intsecond)

{

this->second=hour*60+minute*60+second

}

intgetSecond()

{

returnsecond

}

}

voidmain()

{

Timert1(45),t2(10,25),t3(1,4,10),t4(2,16,0)

cout<<"Fromt1tot2:"<<t2.getSecond()-t1.getSecond()<<endl

cout<<"Fromt3tot4:"<<t4.getSecond()-t3.getSecond()<<endl

}

扩展资料

定义一个日期类:包括年、月、日三个成员变量,显示日期的方法

publicclassDemo{

publicstaticvoidmain(String[]args){

Datedate1=newDate(1994,5,22)

date1.showInfo()

Datedate2=newDate()

date2.year=1995

date2.month=6

date2.day=29

date2.showInfo()

}

}

//日期类:

publicclassDate{

intyear

intmonth

intday

//构造方法

publicDate(intyear,intmonth,intday){

this.year=year

this.month=month

this.day=day

}

publicDate(){

}

publicvoidshowInfo(){

System.out.println(year+"年"+month+"月"+day+"日")

}

}

这里使用的获取时间的函数其实就这一个

time()是C标准库里的一个函数:

C标准库函数

time_t time(time_t *t)

如果t是空指针,直接返回当前时间。如果t不是空指针,返回当前时间的同时,将返回值赋予t指向的内存空间。

因为返回其值表示从UTC(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。然后调用localtime函数将time_t所表示的UTC时间转换为本地时间(我们是+8区,比UTC多8个小时)并转成struct tm类型,该类型的各数据成员分别表示年月日时分秒。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/bake/11419046.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存