zoukankan      html  css  js  c++  java
  • sicily 7618. 9.5 The Time class

    Description

    Design a class name Time. The class contains:

    Data field hour, minute, and second that represent a time.

    A no-arg constructor that creates a Time object for the current time. (The data fields value will represent the current time.)

    A constructor that constructs a Time object with a specified elapsetime since the middle of night, Jan 1, 1970 in seconds. (The data fields value will represent the current time.)

    Three get functions from the data fields hour, minute, and second, respectively.

    class Time
    {
      public:
        Time();
        Time(int totalSeconds);
        int getHour();
        int getMinute();
        int getSecond();
    };

    Hint

    只提交Time类实现,不要提交main()函数。

    又来挖其他班的作业做了……第一次接触到时间库函数(time.h),查了不少资料。

    NOTE:数据类型time_t和long其实是同义词,time(NULL)可以返回距离1970年1月1日的秒数(time_t类型),向localtime函数传入这样的秒数(注意要传time_t类型的指针)会返回一个存储有各类时间信息的tm结构体指针,其中的tm_hour、tm_min等就是依据给出的秒数换算出的当时的时分秒,结构体里的其他成员信息可以去文档里看。

    自己测试了一下,创建一个用默认值的对象可以正常显示出当前时间

    View Code
     1 #include<time.h>
     2 #include<iostream>
     3 using namespace std;
     4 class Time
     5 {
     6     public:
     7         Time();
     8         Time( int totalSeconds );
     9         int getHour();
    10         int getMinute();
    11         int getSecond();
    12     private:
    13         int hour;
    14         int minute;
    15         int second;
    16 };
    17 
    18 Time::Time()
    19 {
    20     time_t timer = time( NULL );
    21     struct tm *tblock = localtime( &timer );
    22     
    23     hour = tblock->tm_hour;
    24     minute = tblock->tm_min;
    25     second = tblock->tm_sec;
    26 }
    27 
    28 Time::Time( int totalSeconds )
    29 {
    30     time_t timer = (time_t)totalSeconds;
    31     struct tm *tblock = localtime( &timer );
    32     
    33     hour = tblock->tm_hour;
    34     minute = tblock->tm_min;
    35     second = tblock->tm_sec;
    36 }
    37 
    38 int Time::getHour()
    39 {
    40     return hour;
    41 }
    42 
    43 int Time::getMinute()
    44 {
    45     return minute;
    46 }
    47 int Time::getSecond()
    48 {
    49     return second;
    50 }
  • 相关阅读:
    【Javascript】javascript学习 三十二 JavaScript 表单验证
    【Javascript】javascript学习 三十四 JavaScript 图像地图
    【Javascript】javascript学习 三十三 JavaScript 动画
    【Javascript】javascript学习 三十六 创建你自己的 JavaScript 对象
    【Javascript】javascript学习 三十七 JavaScript 总结
    【HTML】HTML 教程(系列教程转载)
    【XML】XML概述(连载)
    【Javascript】javascript学习 三十五 JavaScript 计时
    【XML】XML教程
    判断各版本IE的HTML和CSS语句
  • 原文地址:https://www.cnblogs.com/joyeecheung/p/2945338.html
Copyright © 2011-2022 走看看