Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ anonymous union redeclaration error

Tags:

c++

c++11

g++

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.

  1. I saw something related working on windows, why?
  2. What is the best way to implement it so it works well on both (linux/win)?
like image 424
Keloo Avatar asked Nov 29 '25 14:11

Keloo


1 Answers

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.

like image 140
463035818_is_not_a_number Avatar answered Dec 02 '25 05:12

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!