c ++在我的构造函数中获取当前时间

c++ getting current time in my constructor

这是我的问题:

(Enhancing Class Time) Provide a constructor that’s capable of using the current time from the time and localtime functions—declared in the C++ Standard Library header —to initialize an object of the Time class.

这是我的代码: .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 currentTime;

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

做类似的事情

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

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

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

您有点混淆了构造函数代码,当您使用默认构造函数时,成员变量未初始化。

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)
{
}