简体   繁体   English

使用C ++中的自定义元素进行const struct初始化

[英]Const struct initialization with custom elements in C++

I am porting some C code to C++ and I am trying to initialize a struct with some values. 我正在将一些C代码移植到C ++,并且尝试使用一些值初始化结构。 I want the struct to be stored in flash (const) and not in RAM, and its values are typedef'd elements. 我希望该结构存储在flash(const)中而不是RAM中,并且其值是typedef'd元素。

Originally, I had it like this: 最初,我是这样的:

typedef struct
{
    typeA_t elementA;
    typeB_t elementB;
    uint8_t elementC;
} structTypeA_t;

And to instantiate them in flash, I simply did the following: 为了实例化它们,我只做了以下工作:

const structTypeA_t sA = {
    .elementA = ONE,
    .elementB = TWO,
    .elementC = 3
};

I know that this type of initializing is not allowed in C++. 我知道C ++不允许这种类型的初始化。 How can I achieve it in C++? 如何在C ++中实现它?

Designated initializers are not in C++ (yet, but look for C++20). 指定的初始值设定项不在C ++中(但是,请寻找C ++ 20)。 So you do it almost the same way, but without names - position of the argument defines the field it initializes: 因此,您几乎以相同的方式进行操作,但是没有名称-参数的位置定义了它初始化的字段:

const structTypeA_t sA = {ONE,
                          TWO,
                          3
};

If you always need to initialize with the same values, then you can just define the struct like this: 如果您始终需要使用相同的值进行初始化,则只需定义如下结构:

struct structTypeA_t
{
    typeA_t elementA = ONE;
    typeB_t elementB = TWO;
    uint8_t elementC = 3;
};

You can now instantiate it without an initializer: 您现在可以在没有初始化程序的情况下实例化它:

const structTypeA_t sA;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM