Hi guys this question is asked after I did some research on Unions I followed tutorials but for some reason I am getting a compilation error,I have a union but it contains three different structs I want to be able to call the structs data types or even change them
the error is as follows
Description Resource Path Location Type
Field 'a' could not be resolved Main.cpp /nameSpaces line 38 Semantic Error
union numbers{
struct one{
int type = 1;
int a = 6;
};OPTION_INT;
struct two{
int type = 2;
char b = 'a';
};OPTION_CHAR;
struct three{
int type = 3;
double c = 7.2;
};OPTION_DOUBLE;
};
int main()
{
numbers t; // this is fine
int n = t.a; // this is where I get the error
}
Well, OPTION_INT is not related to one because of the ; in front of it. The same applies to the other OPTION_.... So remove the ;.
The second problem is that you cannot initialize members of a union. Everything within the union will be stored in one place. Which of the values are supposed to be used there?
union numbers{
struct one{
int type = 1;
int a = 6;
}OPTION_INT;
struct two{
int type = 2;
char b = 'a';
}OPTION_CHAR;
struct three{
int type = 3;
double c = 7.2;
}OPTION_DOUBLE;
};
int main()
{
numbers number;
number.OPTION_CHAR.type = 5;
}
the error is Description Resource Path Location Type
union member 'numbers::OPTION_CHAR' with non-trivial 'constexpr numbers::two::two()' Main.cpp /nameSpaces line 25 C/C++ Problem
and it's the same for OPTION_INT and OPTION_DOUBLE
Description Resource Path Location Type
use of deleted function 'numbers::numbers()' Main.cpp /nameSpaces line 40 C/C++ Problem
Also this one that does not make sense since sense since I don't have a function named numbers()
The first non-static data member of the union can be initialised with a brace enclosed initialiser
The braces may be omitted if the union is a data member of an aggregate.
A union which does not have a deleted copy/move constructor can be copy/move initialised.
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
union U { int i ; char cstr[23] ; };
U u1 {23} ;
U u2 = u1 ;
u1 = {999} ;
struct S { U u ; double d ; } ;
S s1 { {456}, 78.9 } ;
S s2 { 4567, 89.0123 } ;
s1 = { 11, 22.33 } ;
}
Needless to say, a union may also be initialised via a user-defined constructor: