c++ - union 工作不正常

标签 c++ data-structures structure storage unions

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

相关文章:

c++ - 对于某些生成的项目,msbuild 将文件名解释为中文字符,而不是其他项目

算法:找到包含整个域的最少集合数

c - 尝试将 memset() 结构指针指向 0 时出现段错误

java - 红黑树需要两次遍历

c - 这行代码 "#define LIBINJECTION_SQLI_TOKEN_SIZE sizeof(((stoken_t*)(0))->val)"有什么作用?

C++:字段对象可以在不存储指针的情况下知道它的 "parent"吗?

c++ - 生成随机数对以形成二维随机点

c++ - C++中的加法

c++ - 如何使 Qt Signal 按值发出而不是引用而不会出现编译错误?

c - 堆栈代码无法运行