gpt4 book ai didi

c++ - 如何初始化局部 union 变量?

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:50 36 4
gpt4 key购买 nike

我经常像这样在函数内部定义 union :

union
{
sometype A;
othertype B;
}name;

然后像这样使用它们:

name.A = smth;
name.B = smthelse;

虽然它在 Debug模式下工作,但在 Release模式下它告诉我 union 未初始化并且在 union 成员是指针的某些地方,它甚至崩溃了。那么我该如何初始化它们呢?仅添加就足够了吗'=' 运算符?它不应该有一个默认构造函数吗?

最佳答案

来自 here ,

You can declare and initialize a union in the same statement by assigning an expression enclosed in braces. The expression is evaluated and assigned to the first field of the union.

所以,像这样:

union NumericType
{
int iValue;
long lValue;
double dValue;
};

union NumericType Values = { 10 }; // iValue = 10

但它更常见(许多人会说更好)

union NumericType val;  // declaration
val.dValue = 3.1415; // use union as a double

您遇到错误,因为您似乎在使用 union 就好像它是 struct :)

如果我错了请纠正我,但请阅读here ,例如。

关于c++ - 如何初始化局部 union 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16189393/

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