gpt4 book ai didi

c++ - 如何使用时间类和函数显示时间

转载 作者:行者123 更新时间:2023-11-28 07:01:47 28 4
gpt4 key购买 nike

#include <iostream>
#include <ctime>

using namespace std;

class time
{
protected:
int hr;

public:
void settime()
{
time_t now = time(0);
tm *ltm = localtime(&now);
display(1 + ltm->tm_hour);
}
void display(int a)
{
hr=a;
cout<<hr;
}
};
int main( )
{
time t;
t.settime();

return 0;
}

问题是这样的:提供一个构造函数,该构造函数能够使用 time() 函数中的当前时间(在 C 标准库头文件 time.h 中声明)来初始化时间类的对象。我不太了解这门课,这是真的吗?谁能帮我 ?

最佳答案

实际上这不是一个正确的问题答案(代码)。有问题明确要求创建构造函数。所以不需要单独定义settime()函数。您应该创建一个构造函数并将当前时间代码放入该构造函数中。我在下面给出了一个代码。请清楚你的问题伙计。

#include <iostream>
#include <ctime>

using namespace std;

class time
{
protected:
int hr;

public:

time()
{

time_t now = time(0);

tm *ltm = localtime(&now);

display(1 + ltm->tm_hour);
}
void display(int a)
{
hr=a;
cout<<hr;
}
}
int main( )
{
time t;
return 0;
}

关于c++ - 如何使用时间类和函数显示时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22343443/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com