c++ - Union struct produces garbage and general question about struct nomenclature -


I read about the unions today (today) and it is quite easy to try the sample work that came with them, but its The result was clear and obvious garbage.

The first example is:

  union tests {int int; Structure {four byte 1; Four byte 2; Four byte 3; Four byte 4; } Bytes; };  

Where an int is assumed to be 32 bits. After setting a value, test t; T.Int = 7; and then COAT

Cust & lt; & Lt; T. Bytesbyte 1 & lt; & Lt; Etc ...

Individual bytes, there is nothing displayed, but my computer beeps which is quite odd, I guess.

The second example gave me even worse results.

Union Switchindian {signed short words; Struct {hi four unsigned; Unsigned four; } Information; } Switcher;

In my opinion a little disgruntled, anyway, it is said by the description, when I

Switcher.word = 7656; Setting a value like, cout & lt; & Lt; Switcher data. These & lt; & Lt; Endl

The result was not defined in the ASCII charts as well. Not sure why they are showing

Finally, I got an error when I tried to fix the example, rather than keeping the bytes at the end of the structure, . Therefore

struct {} instead of bytes

I want to write

struct bytes {};

It throws me a big ol 'error What is the difference between these? Since C ++ could have unkempt streaks, at that time, it was very clear that the bytes located at the beginning and the end are the things that give it its name. Except none, this is not my complete answer. then what is it?

Note, technically, reading from a member of a union other than that member who wrote the last time The result was in undefined behavior, so if you have specified a value for the previous int , you can not read a value from byte (for example, the stack There is some discussion on this overflow).

Why are you listening to the beep and watching control letters, so I will not repeat it.

For your final question, struct {} bytes; Announces an example of an unknown structure called byte is similar to saying:

  struct byte type {}; ByteType Bytes;  

Except that you can not specify anywhere else by byte type struct bytes {}; defines a named designated bytes but it does not declare any event.


Comments