简体   繁体   English

如何在C ++中初始化结构内部的union的结构成员?

[英]How to initialize a structure member of a union inside a structure in C++?

I want to port a look-up table of parameters which is an array of structures in C to C++. 我想移植一个参数查找表,它是C到C ++中的结构数组。 I read a few questions and understood that the C-style struct initializer is not allowed in C++. 我读了几个问题,并且理解C ++中不允许使用C风格的struct初始化器。 How can this be ported to C++? 如何将其移植到C ++?

typedef struct {
  char const *property;
  int count;
} TYPE2;

typedef struct {
  int Address;             
  char const *Name;         
  union
  {
    TYPE1 foo;
    TYPE2 bar;
  }u;
} PARAMS;

//Initialize table:
const PARAMS paramTbl[] =
{
  {0x1000, "Param 1", {.bar = {"abc",0}}}, //So on ..
  .
  . 
}

Any help appreciated. 任何帮助赞赏。

You can have a struct/union constructor to initialize with given value. 您可以使用struct / union构造函数来初始化给定值。

struct PARAMS {
  PARAMS(int address, const char *name, const TYPE1 &f) :
                    Address(address), Name(name), u(f)
  {
  }
  PARAMS(int address, const char *name, const TYPE2 &b) :
                    Address(address), Name(name), u(b)
  {
  }

  int Address;
  char const *Name;         
  union union_name
  {
    union_name(const TYPE1 &f) : foo(f) {}
    union_name(const TYPE2 &b) : bar(b) {}
    TYPE1 foo;
    TYPE2 bar;
  }u;
};

const PARAMS paramTbl[] {
  PARAMS(0x1000, "Param1", TYPE1("abc", 0)),
};

Complete example here 在这里完成示例

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

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