Reputation: 1408
I want to create a struct that can be used to store 3D coordinates or a linear equation. Here is the code:
struct myStruct {
union {
// coordinates (3d)
struct {
int x,y,z;
};
// linear equation (ax+b)
struct {
int a,b,x;
};
};
};
And I get the following error:
error: redeclaration of ‘int myStruct::<anonymous union>::<anonymous struct>::x’
I'm on linux mint 18.04, g++ (5.4.0), compile with --std=c++11.
I understand the problem. But have few questions.
Upvotes: 3
Views: 464
Reputation: 7017
Just to complement the answer by user463035818. You can simplify your union a bit, by declaring the members directly, e.g.:
struct myStruct {
union {
// coordinates (3d)
struct {
int x,y,z;
} coord;
// linear equation (ax+b)
struct {
int a,b,x;
} lin_eq;
};
};
Upvotes: 1
Reputation: 123069
Just give them names. This should be fine:
struct myStruct {
union {
struct coordinates { int x,y,z; };
struct linear_equation { int a,b,x; };
coordinates coord;
linear_equation lin_eq;
};
};
I also allowed myself to add some members to the union. However, the two structs have members of same types and quantity, so imho entering the trouble of using a union is questionable.
Upvotes: 1