如何在 C++ 中初始化静态结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5707683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:41:47  来源:igfitidea点击:

how to initialize a static struct in c++?

c++staticstructinitializationmember

提问by filippos

I have managed to initialize correct any variable of basic type(i.e. int, char, float etc) but when declaring a little complex variable all i can see is errors.

我已经设法初始化正确的任何基本类型的变量(即 int、char、float 等),但是在声明一个复杂的变量时,我只能看到错误。

In the header file timer.h i declare

在头文件 timer.hi 中声明

class AndroidTimerConcept {
...
private:
    //struct that holds the necessary info for every event
    struct Resources{
        timer_delegate_t membFunct;
        void *data;
        int size;
        millis_t time;
    };
    //declaring an array of 10 Resources structs
    static struct Resources ResData;
    static int best;
...
}

inside the timer.cpp file

在 timer.cpp 文件中

#include <iostream>
#include "timer.h"
using namespace std;


int AndroidTimerModel::best=1000;
struct Resources AndroidTimerModel::ResData.size; //line 17!!
//constructor that initializes all the necessary variables

AndroidTimerModel::AndroidTimerModel()
{
    signal(SIGALRM,signalHandler);

    for(int i=0; i<MAX_EVENTS; i++)
    {
        //ResData.data=NULL;
        ResData.size=-1;
        //ResData.time=-1;
    }

    best=1000;

}

when compiling the .cpp file i get the error: timer.cpp:7: error: expected initializer before ‘.' token

编译 .cpp 文件时,我收到错误:timer.cpp:7: error: expected initializer before '.' 令牌

Any suggestions would be really helpful.

任何建议都会非常有帮助。

btw i use g++

顺便说一句,我使用 g++

回答by Ben Voigt

You don't separately define individual instance members within a static member.

您不会在静态成员中单独定义单个实例成员。

This should be enough:

这应该足够了:

AndroidTimerModel::Resources AndroidTimerModel::ResData;

回答by BeeOnRope

You can use a struct initializer in C++, but only in the pre-C99 style (i.e, you cannot use designated initializers). Designated intializers, which allow you to specify the members to be initialized by name, rather than relying on declaration order, were introduced in C99, but aren't part of any C++ standard at the moment (belying the common assumption that C++ is a superset of C).

您可以在 C++ 中使用结构初始化器,但只能使用 C99 之前的样式(即,您不能使用指定的初始化器)。指定的初始化器,允许您指定要按名称初始化的成员,而不是依赖于声明顺序,是在 C99 中引入的,但目前不是任何 C++ 标准的一部分(与 C++ 是超集的常见假设背道而驰C)。

If you are willing to write non-portable C++ code that specifically targets g++, you can always use the GCC-specific extensionwhich has the same functionality as designated constructors. The syntax is like this:

如果您愿意编写专门针对 g++ 的非可移植 C++ 代码,您始终可以使用与指定构造函数具有相同功能的GCC 特定扩展。语法是这样的:

struct value_t my_val = { member_a: 1, member_b: 1.2f };

This referenceprovides a pretty good overview of both types of initialization in the C context.

该参考资料很好地概述了 C 上下文中的两种初始化类型。

Here's an excerpt that shows both the earlier (without designators) and C99 styles:

这是一个摘录,同时显示了较早的(无指示符)和 C99 样式:

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99) initialize the struct members declared after the one initialized by the previous expression.

初始化结构时,列表中的第一个初始化器初始化第一个声明的成员(除非指定了指示符)(自 C99 起),并且所有后续没有指示符的初始化器(自 C99 起)初始化由前一个初始化的成员之后声明的结构成员表达。

struct point {double x,y,z;} p = {1.2, 1.3}; // p.x=1.2, p.y=1.3, p.z=0.0
div_t answer = {.quot = 2, .rem = -1 };      // order of elements in div_t may vary

In some cases you may need to write some code to initialize a structure, and in this case you can use the result of a function, like:

在某些情况下,您可能需要编写一些代码来初始化结构,在这种情况下,您可以使用函数的结果,例如:

struct Resources AndroidTimerModel::ResData = function_that_acts_like_a_constructor();

回答by quamrana

You need to declare and define a constructor for struct Resources. eg

您需要为 struct 声明和定义一个构造函数Resources。例如

struct Resources{
    timer_delegate_t membFunct;
    void *data;
    int size;
    millis_t time;
    Resources():membFunct(0), data(0), size(0), time(0) {}
    ....
};

回答by Scott Langham

Is it AndroidTimerModel or AndroidTimerConcept, you can't use different names and expect the compiler to think they're the same thing.

是 AndroidTimerModel 还是 AndroidTimerConcept,您不能使用不同的名称并期望编译器认为它们是同一回事。

You need to scope the name Resources, it's not in global scope, it's in the scope of the AndroidTimerModel class:

您需要限定名称 Resources 的范围,它不在全局范围内,而是在 AndroidTimerModel 类的范围内:

AndroidTimerModel::Resources AndroidTimerModel::ResData;

I suggest you give Resources a constructor:

我建议你给 Resources 一个构造函数:

struct Resources{
    Resources(timer_delegate_t aMembFunct, void* aData, int aSize, millis_t aTime )
      : membFunc(aMembFunct)
      , data(aData)
      , size(aSize)
      , time(aTime)
    {}
    timer_delegate_t membFunct;
    void *data;
    int size;
    millis_t time;
};

And you can then define Res in your .cpp as:

然后您可以在 .cpp 中将 Res 定义为:

AndroidTimerModel::Resources AndroidTimerModel::ResData(/* params here */);

回答by pmdj

You need to initialise the wholestruct variable, something like this:

您需要初始化整个结构变量,如下所示:

AndroidTimerConcept::Resources AndroidTimerModel::ResData = { NULL, NULL, 0, 0 };

回答by pmdj

Why is your structpart of a class? I would make it global outside of the class.

为什么你struct是班级的一部分?我会在课堂之外让它成为全球性的。

memset(&structname, 0, sizeof(structname));will initialize your structure to 0.

memset(&structname, 0, sizeof(structname));将您的结构初始化为 0。