gpt4 book ai didi

c++ - union 工作不正常

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:33 25 4
gpt4 key购买 nike

这是我的代码。它在 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/

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