1. 程式人生 > 其它 >菜鳥的練習1

菜鳥的練習1

技術標籤:C++相關學習

例子1:

  1. 寫一個UserTime類,返回當期系統時間。
  2. 寫main函式,呼叫UserTime的結果獲取當前系統時間,並列印
    XXXX-XX-XX XX:XX:XX:XXXXXX

usertime.h

#ifndef TIME_H__
#define TIME_H__
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;

typedef struct
{
    int year;
    int mon;
    int day;
    int hour;
    int min;
    int sec;
} TIME_TYPE;


class UserTime
{
public:
    UserTime(){};
    ~UserTime(){};

    static int GetSysTime(TIME_TYPE *tm_type);

private:
};

#endif

usertime.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include "usertime.h"

using namespace std;


int UserTime::GetSysTime(TIME_TYPE *atime)
{

   
   time_t rawtime;
   struct tm* tm_type;
   struct timeval ttime;

   time (&rawtime);
   tm_type = localtime (&rawtime);
    
    gettimeofday(&ttime,NULL);

    printf("當前時間為:%04d-%02d-%02d %02d:%02d:%02d:%d\n",
           tm_type->tm_year+1900, tm_type->tm_mon+1, tm_type->tm_mday,
           tm_type->tm_hour, tm_type->tm_min, tm_type->tm_sec,
           (ttime.tv_usec/1000));
    
   
    

        return 0;
}

main.cpp

#include<iostream>

#include"usertime.h"
using namespace std;


int main()
{
    //UserTime *usertime = new UserTime();
    
    TIME_TYPE NowTime;
    UserTime::GetSysTime(&NowTime);
    //delete usertime;
    return 0;
}

在這裡插入圖片描述