gpt4 book ai didi

c++ - 如何在 const struct 中初始化 union ?

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:10 61 4
gpt4 key购买 nike

 const struct EbmlSyntax {
uint32_t id;
EbmlType type;
int list_elem_size;
int data_offset;
union {
uint64_t u;
double f;
const char *s;
const struct EbmlSyntax *n;
} def;
} ;

我必须使用上面的 const 结构,并想使用

创建一个常量结构

{ EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.def.s = "(none)"} }

但是,VS8.0编译器报错error C2143: syntax error : missing '}' before '.'当我编译 C++ 项目时。

我尝试了几种方法,但是,我只找到将 char * 转换为 uint64_t(分配给第一种类型)的方法,

(uint64_t)("none")

我可以使用 union 。这种方法安全吗?我使用 VS 调试工具检查了这个和其他 struct-union 对象的结构。似乎可以正确解释 struct 和 union 的成员。

最佳答案

您只能使用该语法初始化 union 的第一个元素。您需要另一种方法。

关于c++ - 如何在 const struct 中初始化 union ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14456163/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com