Howdy~
I just found when I want to initialize variables inside a union or struct compiler will report an error, why couldnt we do that ??? :rolleyes:
Printable View
Howdy~
I just found when I want to initialize variables inside a union or struct compiler will report an error, why couldnt we do that ??? :rolleyes:
Either declare the members static (remember, unions can't have static members) or, create an object of the particular struct/union and initilize those variables.
Some code would help too.
thanx. but I wonder why we couldnt initialize variable just as class ? :confused:Quote:
Originally posted by Eibro
Either declare the members static (remember, unions can't have static members) or, create an object of the particular struct/union and initilize those variables.
Some code would help too.
You can, but maybe not in a constructor as you may be thinking.
Post some code.
for example:Quote:
Originally posted by Eibro
You can, but maybe not in a constructor as you may be thinking.
Post some code.
if we run this code will get an error, why couldnt we do that ???Code:union myUnion
{
int a=0;
bool b;
char c;
}
You can specify a union constructor as you would with a struct or class....do so and set the member with the largest varible type to zero.
Code:#include <iostream>
union myUnion
{
myUnion():a(0){}
int a;
bool b;
char c;
};
int main() {
myUnion u;
std::cout << "As int " << u.a << std::endl;
std::cout << "As bool " << u.b << std::endl;
std::cout << "As char " << u.c << std::endl;
}