我无法初始化自定义类型的常量数组。代码如下:
union chk {
struct{
int a : 4;
int b : 12;
}stNative;
int nVal;
};
const chk obj[2] = {0x1234, 0x6789};
int main() {
cout << obj[0].nVal<<endl;
}
执行上述代码时,我得到一些随机值。 我无法理解发生这种情况的原因以及如何解决它。 上述代码的O/P为:30868
最佳答案
声明中的初始化将值分配给第一个 union 成员stNative
,这是一个具有两个值的结构。您已为第一个结构成员 a
提供了溢出的值。这个小更新将初始化两个结构成员。
#include <iostream>
using namespace std;
union chk {
struct{
int a : 4;
int b : 12;
}stNative;
int nVal;
};
const chk obj[2] = {{0x1, 0x234}, {0x6, 0x789}};
int main() {
// Undefined behaviour bellow while reading nVal
cout << std::hex << obj[0].nVal<<endl;
}
// Output: 2341
C++ 中不允许类型双关。如果初始化 union 成员stNative
,则只能读取它,不允许读取nVal
。使用std::bit_cast
或用于类型双关的memcpy。
关于c++ - 初始化 struct 类型的常量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73246125/