这是我的代码。它在 C 中运行良好,但在 C++ 中表现得像结构。
#include<iostream>
using namespace std;
int main()
{
union myunion
{
int B;
double PI;
};
union myunion numbers;
numbers.PI = 3.14;
numbers.B = 12;
/* now storage of PI should be over-written */
cout<<numbers.PI<<endl;
cout<<numbers.B<<endl;
/* Output is 3.14 */
/* 12 */
/* Why it is behaving like Structures ? */
return 0;
}
最佳答案
评论者提到,Cppreference on union
states :
it's undefined behavior to read from the member of the union that wasn't most recently written.
这就是为什么您的程序会这样:这是未定义的行为。它可以显示先前的值、崩溃或介于两者之间的任何内容。
numbers.PI = 3.14;
numbers.B = 12;
cout<<numbers.PI<<endl; // undefined behaviour
关于c++ - union 工作不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41583544/