说工会成员一次只能被操纵一个人是什么意思?

JK *_*nic 3 c++ visual-c++ unions c++11

我只是在阅读工会和堆叠背后的理论。这本书(E Balagurusamy撰写的《用C ++进行面向对象的程序设计》)说:“一个联合的成员一次只能被操纵一次”。但是我在和工会混在一起。我做到了没有错误。

#include <iostream>
#include <iomanip>
#include "ConsoleApplication1.h"

using namespace std;
//user defined data types
#define writeln(x)(cout<<x<<endl)
union result
{
    int marks;
    char grade;
    float percent;
};
int main()
{  
    result result;
    result.marks = 90;
    result.grade = 'a';
    writeln(result.grade);
    writeln(result.marks);
}
Run Code Online (Sandbox Code Playgroud)

因此,请您澄清一下该声明的含义。谢谢:)。

Ser*_*sta 6

这意味着您正在调用未定义的行为。让我们看看每一行代码会发生什么:

result result;         // ok, you have declared an union
result.marks = 90;     // ok, result.marks is defined
result.grade = 'a';    // ok, result.grade is defined, but result.mark is no longer
writeln(result.grade); // ok, access to the last written member of the union
writeln(result.marks); // UB: access to a member which is not the last writter
Run Code Online (Sandbox Code Playgroud)

UB对新来者真的不友好,因为可能发生任何事情:

  • 编译器可以检测到该问题并发出警告或错误(但并不需要...)
  • writeln(result.marks)可能会写90'a'字符(97)的代码,或者什么也不会写,或者甚至终止程序

随着任何事情的发生,您可以在一次运行中获得预期的行为,然后又获得另一种行为。

长话短说:不要玩这个...