C++ Structure Initialization (16个答案)
上个月关闭。
我正在尝试将一些用于嵌入式目标的旧版C代码迁移到C++中以解决兼容性问题,并且在C++中我遇到一些联合问题。
在我们的项目中,我们采用以下联合形式来减少RAM使用量:
typedef union unionTest
{
struct
{ uint32_t nField1:5
; uint32_t nField2:4
; uint32_t nField3:23
;}
; uint32_t nRaw ///< Raw data
;} unionTest;
// A global variable for configuration
unionTest myCUnion = {.nField1 = 1, .nField2 = 2, .nField3 = 3 };
这很好用,易于使用,并且编译器在编译时将位字段初始化为正确的值
然后在转换为C++时
typedef union unionTest
{
struct
{ uint32_t nField1:5
; uint32_t nField2:4
; uint32_t nField3:23
;}
; uint32_t nRaw ///< Raw data
;} unionTest;
// Using const saves RAM, one of the reason to switch to C++
const unionTest myCppUnion = {.nField1 = 1, .nField2 = 2, .nField3 = 3 }; // Error
不再起作用,我出现“初始化太多”错误。无论如何,要保持C行为。我知道ISO C++禁止使用匿名结构,但是更改此结构会对代码库产生巨大影响,目前还不被认为很重要。
我还尝试了一个命名结构
typedef union unionTest
{
struct notAnonymous
{ uint32_t nField1:5
; uint32_t nField2:4
; uint32_t nField3:23
;} notAnonymous
; uint32_t nRaw ///< Raw data
;} unionTest;
// Using const saves RAM, one of the reason to switch to C++
const unionTest myCppUnion2 = {.notAnonymous.nField1 = 1, .notAnonymous.nField2 = 2, .notAnonymous.nField3 = 3 }; // expected primary-expression before '.' error
const unionTest myCppUnion3 = { .notAnonymous = { .nField1 = 1, .nField2 = 2, .nField3 = 3 } }; // Compiles
而且我找不到保持原始C行为的解决方案。
我尚未测试解决方案“myCppUnion3”是否正确填充了位域,但我更感兴趣的是找到解决方案“myCppUnion”的解决方案/解决方法
如果任何人有任何线索,我都会乐意接受!
I have a "too many initializers" error.
解决方案很简单。您需要使用一组花括号来明确表示您正在初始化联合中的嵌套类:
{ // the union
{ // the struct
.nField1 = 1, // members of the struct
.nField2 = 2,
.nField3 = 3,
}
};
I know that anonymous structures are prohibited by ISO C++
确实,这是C++必须解决的另一件事。修复该问题后,可以像示例中那样为结构使用指定的初始化符号。
您可能会遇到的第三个问题是C++不允许从不 Activity 的工会成员中读取内容,这似乎是您在C中所做的事情。
第四个潜在的问题是,如果您曾经切换过编译器,则可能会发现位域的顺序发生了变化,如果程序依赖于特定的顺序,则可能会出现问题。