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

标签 c++ class

#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/

相关文章:

c++ - 计数循环?

c++ - DXGI Desktop Duplication API 何时将区域识别为移动区域?

java - 让父类(super class)使用子类使用的枚举

c - 如何在 Eclipse 上创建 C 类

c++ - 将带有模板的自定义类插入 std::map

c# - 在该类的构造函数中实例化类变量

javascript - Odoo 更改基本 JavaScript 方法

c++ - 通过逻辑层中的类转发 QProgressBar 更新的正确方法是什么?

c++ - GDCM:我想对图像做一个简单的锐化过滤器,但不知道如何改变像素值

c++ - sizeof 在编译不同的程序时为结构返回不同的值