【问题标题】:c++ getting current time in my constructorc++ 在我的构造函数中获取当前时间
【发布时间】: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(&currenttime);
localtime_s(&timeinfo, &currenttime);

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


【解决方案1】:

您混淆了 ctor 代码,当您使用默认 ctor 时,成员变量未初始化。

Time::Time()
{
    // Initialize to the current time
    time_t currenttime;
    struct tm timeinfo;
    time(&currenttime);
    localtime_s(&timeinfo, &currenttime);
    hour = timeinfo.tm_hour;
    minute = timeinfo.tm_min;
    second = timeinfo.tm_sec;
}

// Modified to use initializer list
Time::Time(int h, int m, int s) :
    hour(h), minute(m), second(s)
{
}

【讨论】:

  • @Aconcagua 是的,我同意。我只是从原始问题中复制并粘贴。
【解决方案2】:

您的时间未正确初始化,这就是您获得这些值的原因...

当你这样做时

Time currentTime;

您正在使用默认构造函数创建 Time 对象,而字段未初始化......

做类似的事情

private:
int hour{0};
int minute{0};
int second{0};

另一个技巧可能是从默认的 const 调用第二个 const,因为您在其中放置了用于初始化对象的逻辑...

Time::Time() : Time(0, 0, 0)
{}

【讨论】:

  • 很确定默认构造函数应该像第二个那样进行时间初始化 - 而后一个应该只用构造函数参数初始化对象......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 2017-05-28
  • 2011-07-05
相关资源
最近更新 更多