设为首页 加入收藏

TOP

一个计时器的实现
2014-11-23 23:55:19 来源: 作者: 【 】 浏览:15
Tags:一个计时器 实现

直接上代码

定义头文件:

//: C09:Cpptime.h

// From Thinking in C++, 2nd Edition

// Available at http://www.BruceEckel.com

// (c) Bruce Eckel 2000

// Copyright notice in Copyright.txt

// A simple time class

#ifndef CPPTIME_H

#define CPPTIME_H

#include

#include

class Time {

time_t t;

tm local;

char asciiRep[26];

unsigned char lflag, aflag;

void updateLocal() {

if(!lflag) {

local = *localtime(&t);

lflag++;

}

}

void updateAscii() {

if(!aflag) {

updateLocal();

strcpy(asciiRep,asctime(&local));

aflag++;

}

}

public:

Time() { mark(); }

void mark() {

lflag = aflag = 0;

time(&t);

}

const char* ascii() {

updateAscii();

return asciiRep;

}

// Difference in seconds:

int delta(Time* dt) const {

return int(difftime(t, dt->t));

}

int daylightSavings() {

updateLocal();

return local.tm_isdst;

}

int dayOfYear() { // Since January 1

updateLocal();

return local.tm_yday;

}

int dayOfWeek() { // Since Sunday

updateLocal();

return local.tm_wday;

}

int since1900() { // Years since 1900

updateLocal();

return local.tm_year;

}

int month() { // Since January

updateLocal();

return local.tm_mon;

}

int dayOfMonth() {

updateLocal();

return local.tm_mday;

}

int hour() { // Since midnight, 24-hour clock

updateLocal();

return local.tm_hour;

}

int minute() {

updateLocal();

return local.tm_min;

}

int second() {

updateLocal();

return local.tm_sec;

}

};

#endif // CPPTIME_H ///:~

使用示例:

//: C09:Cpptime.cpp

// From Thinking in C++, 2nd Edition

// Available at http://www.BruceEckel.com

// (c) Bruce Eckel 2000

// Copyright notice in Copyright.txt

// Testing a simple time class

#include "head.h"

#include

using namespace std;

int main() {

Time start;

for(int i = 1; i < 1000; i++) {

cout << i << ' ';

if(i%10 == 0) cout << endl;

}

Time end;

cout << endl;

cout << "start = " << start.ascii();

cout << "end = " << end.ascii();

cout << "delta = " << end.delta(&start);

} ///:~

摘自 yucan1001

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇一道容易出错的笔试题 下一篇一步一步写算法(之可变参数)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: