C++ ~ Time类实例研究
来源:互联网 发布:c语言输出1到100的素数 编辑:程序博客网 时间:2024/06/05 18:24
Time类的定义:
类中的定义包含成员函数Time、setTime、printUniversal、printStandard的函数原型,以及private unsigned int成员hour、minute、second。只能通过Time类的成员函数访问它的private数据成员。
下面的例子是我的简单Time类演示代码:
time.h文件
#ifndef __TIME_H__#define __TIME_H__class Time{public:Time();void setTime(int, int, int);void printUniversal() const;void printfStandard() const;private:unsigned int hour;unsigned int minute;unsigned int second;};#endif
time.cpp文件:
#include<iostream>#include<string>#include<iomanip>#include<stdexcept>#include"time.h"using namespace std;Time::Time():hour(0), minute(0), second(0){}void Time::setTime(int h, int m, int s){if ((h >= 0 && h < 24) && (m >= 0 && m < 60) && (s >= 0 && s < 60)){hour = h;minute = m;second = s;}else{throw invalid_argument("number out of range");}}void Time::printUniversal()const{cout << setfill('0') << setw(2) << hour << ":" << setw(2) //setfill指定输出宽域大于输出整数值所需的填充字符<< minute << ":"<<setw(2) << second; //setw控制输出宽域,对紧接显示的值起作用(注意包含头文件<iomanip>)}void Time:: printfStandard() const{cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":"<< setfill('0') << setw(2) << hour << ":" << setw(2) << minute<< ":" << setw(2) << second << (hour < 12 ? "AM" : "PM");}
test.cpp文件:
#include<iostream>#include<string>#include<iomanip>#include<stdexcept>#include"time.h"using namespace std;int main(){Time t;cout << "the init time is: ";t.printUniversal();cout << "\nthe time is: ";t.printfStandard();t.setTime(15, 12, 50);cout << "\n\nthe init time is: ";t.printUniversal();cout << "\nthe time is: ";t.printfStandard();cout << endl;try{t.setTime(50, 12, 50);}catch (invalid_argument &e){cout << "\nException: " << e.what() << endl;}cout << endl;return 0;}运行结果:
阅读全文
1 0
- C++ ~ Time类实例研究
- 【linux c开发】time时间处理实例
- C-向服务器写log | time库函数研究
- Cookie--c#.net深入研究实例
- time.c
- 实例研究
- C local time & UTC time
- C/C++中时间类time.h
- Objective-C 基础:Time时间类
- Object-C类实例
- 【C#】类与实例
- python time模块使用实例
- c语言 time.h
- C Run-time library
- time.c相关
- C run-time library
- C语言-time.h
- c library-time.h
- MyBatis之级联
- Log4j入门之001
- 文章标题
- 字段的数据类型
- PAT (Advanced Level) Practise
- C++ ~ Time类实例研究
- BigInteger/BigDeciaml/Calendar/Data/System常用类
- 【C语言】"for" "while" "do……while"
- zubax_gnss移植到STM32F407
- 使用React Native 和 微信小程序 编写的一款阅读类app ———《轻松一刻》
- Linux平台下搭建FTP服务器
- PAT (Advanced Level) Practise
- 2017.11.5总结
- 文章标题