【发布时间】:2019-04-16 15:53:05
【问题描述】:
这是我的问题:
(增强类时间)提供一个能够使用当前时间的构造函数 时间和本地时间函数——在 C++ 标准库头文件中声明——初始化 Time 类的对象。
这是我的代码: .h 文件
#ifndef TIME
#define TIME
class Time
{
public:
Time();
Time(int, int, int);
void Display();
private:
int hour, minute, second;
};
#endif // !1
.cpp 文件
#include "Time.h"
#include <ctime>
#include <iostream>
using namespace std;
Time::Time(){}
Time::Time(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
time_t currenttime;
struct tm timeinfo;
time(¤ttime);
localtime_s(&timeinfo, ¤ttime);
h = timeinfo.tm_hour;
m = timeinfo.tm_min;
s = timeinfo.tm_sec;
}
void Time::Display()
{
cout << hour << ":" << minute << ":" << second << endl;
}
main.cpp 文件
#include <iostream>
#include "Time.h"
#include <ctime>
int main()
{
Time currentTime;
currentTime.Display();
system("pause");
return 0;
}
输出:
-858993460:-858993460:-858993460
【问题讨论】:
-
获取读取
time()的代码并将其移动到您的默认ctor 中。除了更改最后 3 行以分配成员变量。 -
h/m/s 的负值是否有意义?如果你说“是”,那么 int 很好,否则我更喜欢 unsigned int 来反映这个问题。也许您还想检查 h 必须小于 24、m
标签: c++ class constructor ctime