工会不能正常工作

red*_*b17 1 c++ storage structure unions data-structures

这是我的代码.它适用于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;
}
Run Code Online (Sandbox Code Playgroud)

Tas*_*Tas 6

评论者提到了,以及关于union各州的Cppreference:

从最近编写的联合成员中读取它是未定义的行为.

这就是为什么你的程序表现如此:它是未定义的行为.它可以显示之前的值,或崩溃,或介于两者之间的任何内容.

numbers.PI = 3.14;
numbers.B = 12; 

cout<<numbers.PI<<endl; // undefined behaviour
Run Code Online (Sandbox Code Playgroud)

  • @ user7402737你不应该避免使用联合会,但你不应该访问最近写的联盟成员. (2认同)