first, let me show you a third style:
union name
{
int x;
char c;
};
name n; //name is a type. I would say this one is the 'not anonymous' union.
your first style is sort of C style, where you append the name of a *variable* not a *type* at the end. price is a *variable* of type *unnamed union* ... you can say price.yen = 13; I would call this an anonymous union as well, since unlike the one above, its not a named type.
your second one ... I have never seen this style, it has neither a type nor a variable and its like it was just inherited into the class (eg yen and dollars are treated as class variables). Which is fine.
So if you read on below it (see below), they claim that price is the name of the union ( I disagree, its the name of a variable of an unnamed union to me) and the second one is totally anon and absorbed by the class.
The only difference between the two types is that in the first one, the member union has a name (price), while in the second it has not. This affects the way to access members dollars and yen of an object of this type. For an object of the first type (with a regular union), it would be:
1
2
book1.price.dollars
book1.price.yen
whereas for an object of the second type (which has an anonymous union), it would be:
1
2
book2.dollars
book2.yen
|
To be honest, unions are not used a lot in modern c++. The standard banned the one thing unions did well from being used, making them sort of meh for most tasks.
in defense of why I say price is a variable, consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
struct book1_t {
char title[50];
char author[50];
union {
float dollars;
int yen;
} price, money;
} book1;
int main()
{
book1.money.yen = 10;
book1.price.dollars = 12.34;
|