如何在 VC++ 中为联合赋值

How to assign value to union in VC++

在 C 中有一个 union 并嵌入到 C++ 中,如下所示:

typedef union MyUnion MyUnion_;
union MyUnion{
    ULONG   mLong;
    char    mChar;
...
};

当我尝试像这样初始化它时:

MyUnion_ test;
test = (MyUnion_)NULL;

这可以通过 Mingw32 编译,但给出

error: C2440: 'type cast': cannot convert from 'void *' to 'MyUnion_'

在 VC++ (VS2015) 中。那么如何在 VC++ 编译器中转换和初始化 union

现在我是这样做的:

MyUnion_ test;
test.mLong = NULL;

但这会使程序在将 union 作为参数传递时看起来很糟糕。

void test(MyUnion_ u)

ULONG i = 0;

// mingw32
test((MyUnion_)i);

// vc++
MyUnion_ temp;
temp.mLong = i;
test(temp);

默认构造函数?

typedef union MyUnion MyUnion_;
union MyUnion {
    ULONG   mLong;
    char    mChar;
    MyUnion(): mLong(0) {}
};

int main()
{
    MyUnion_ temp;
    return 0;
}

使用支持 C++11 统一初始化语法的编译器,您可以使用带有单个值的花括号初始化器,它将用于初始化联合的第一个非静态字段……

MyUnion test{ 0 };

您可以在上面的代码中使用 NULL 而不是零,但是用 NULL.[= 初始化 mLong(这是一个 ULONG)似乎令人困惑23=]

如果必须在声明变量后设置变量,也可以在赋值语句中使用花括号初始化……

MyUnion test{ 0 };

// ...

test = { 3 };

请注意,大括号初始化器语法也可能在旧编译器中可用,这些编译器为过去称为 C++0x 的内容提供实验性支持

Visual Studio 2015 C++ 支持大括号初始化程序,除非您正在编译具有 .c 扩展名的文件或正在使用 /TC switch to compile as C code(而不是 C++ 代码)。

旧的 C++(和 C)编译器

使用不支持大括号初始化的编译器时,可以在声明中使用旧的赋值初始化语法...

MyUnion_ test = { 0 };

…但不在赋值语句中。

转换为联合类型

根据 this IBM Knowledge Center article 转换为联合类型是对 C99 的扩展“...实施以促进使用 GNU C 开发的程序的移植”——这表明它不是标准 C。

Microsoft documentation 表示在 C 中没有针对联合、结构或数组的合法转换

C++ 中,如果存在合适的构造函数,则可以转换为联合类型...

union MyUnion {
   unsigned long   mLong;
   char            mChar;

   MyUnion(unsigned long val) { mLong = val; };
};


// valid cast 
test = (MyUnion)3ul;

// invalid cast - no suitable constructor exists
void * ptr = 0;
test = (MyUnion)ptr;