初始化 struct 类型的常量数组

har*_*rsh 2 c++ data-structures

我无法初始化自定义类型的常量数组。以下是代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

执行上述代码时,我得到一些随机值。我无法理解发生这种情况的原因以及如何解决它。上述代码的O/P是:30868

S.M*_*.M. 5

声明中的初始化将值分配给第一个联合成员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
Run Code Online (Sandbox Code Playgroud)

C++ 中不允许类型双关。如果初始化联合体成员stNative,则只能读取,nVal不允许读取。使用std::bit_castormemcpy进行类型双关。