您的位置:首页 > 编程语言 > C语言/C++

c++实现显示系统当前时间

2008-11-25 13:28 281 查看
小朋友托我写的显示时间的控制台小程序,不熟悉时间类,查了下资料,参考上一篇转载博文.另外关于析构函数有点新的收获,通过指针申请的内存空间在主函数退出前需要显示地去释放空间以调用析构函数.而简单的申明对象在主函数退出时会自动调用析构函数. 下面是我显示系统当前时间的源代码.

/*

程序功能:

显示系统当前时间

*/

#include <iostream>

#include "time.h"

using namespace std;

class Clock

{

public:

Clock(time_t pt=time(NULL))

{

t=pt;

local=localtime(&t);

nHour=local->tm_hour;

nMinute=local->tm_min;

nSecond=local->tm_sec;

}

~Clock()

{

cout<<"clock destruction OK!"<<endl;

}

private:

time_t t;

tm *local;

int nHour;

int nMinute;

int nSecond;

friend ostream& operator<<(ostream& out,Clock& clock)//重载操作符<<,输出时间

{

out<<clock.nHour<<":";

if(clock.nMinute<10)

out<<"0";

out<<clock.nMinute<<":";

if(clock.nSecond<10)

out<<"0";

out<<clock.nSecond;

out<<endl;

delete &clock;//释放空间

return out;

}

};

int main()

{

Clock *clock=new Clock();

cout<<"Local Time is:"<<endl;

cout<<*clock;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: