English 中文(简体)
A. 在一个类别中引入静态阻塞
原标题:Initializing static struct tm in a class

我想将“ t”作为一类固定变量。 每天用一整天的读写和尝试,但是仍然可以工作: 如果有人能够指出我正在做的错误,那将不胜感激。

在我的班子里,我公开宣布:

static struct tm *dataTime;

在主机中,我尝试用系统时间加以界定和初步确定,以便暂时测试(实际时间在运行时进入)

time_t rawTime;
time ( &rawTime );
tm Indice::dataTime = localtime(&rawTime);

但是,我似乎可能利用外部职能。

main.cpp:28: error: expected constructor, destructor, or type conversion before ‘(’ token

我如何将价值观引入一个等级的固定门口?

最佳回答

您可以履行以下职能:

tm initTm() {
    time_t rawTime;
    ::time(&rawTime);
    return *::localtime(&rawTime);
}

tm Indice::dataTime = initTm();

避免出现可能的联系问题,使职能静态化,或将其置于一个没有名称的空间。

问题回答
struct tm get_current_localtime() {
    time_t now = time(0);
    return *localtime(&now);
}

struct tm Indice::dataTime = get_current_localtime();

2. 满足功能中的整个事物,并使用其初始固定成员:

tm gettime() {
    time_t rawTime;
    time ( &rawTime );
    return localtime(&rawTime);
}

tm Indice::dataTime = gettime();

而您不需要(因而也没有必要)在C++中用<代码>struct<>/code>预先确定结构使用:tm就足够了,无需struct tm

您可以任意要求外部职能。 要么在您的<代码>main()功能中进行初始化,要么在<代码>tm周围形成一个包装类别,并安装一个能够初步化的结构。

并请注意,struct tm 是一条 t的指点。 从当地时间返回是一个单一州点,如果你或其他任何人再次打电话,其内容将发生变化。

加入:

namespace {
  class Initializer {
    public:
      Initializer() { 
        time_t rawtime; time(&rawtime);
        YourClass::dataTime = localtime(&rawtime);
      }
  };
  static Initializer myinit();
}

当标书在运行时间启动时,即称为构造者,然后按照你的意愿确定“全球”变量数据时间。 请注意,匿名造名空间有助于防止出现假名和神秘人物的潜在冲突。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签